#include "MissionPart.h"
#include "Mission/MissionManager.h"
#include "../Character/Player.h"
#include "../Character/drop/DropMgr.h"
#include "ProtoBuffer/AllProtocol.h"
#include "Answer/AnswerMgr.h"
#include "PlayerMgr.h"
#include "Common/Utility/TimeUtility.h"
#include "base/core/Profiler.h"
#include "Common/TableData/ConstantConstantCfg.h"
#include "Common//TableData/TasktypeTasktypeCfg.h"
#include "Character/HuoYueDuPart.h"
#include "Character/monster/Monster.h"
#include "ServerModule/LogicActivityModule.h"
#include "Common/TableData/AreaAreaCfg.h"
#include "Character/monster/MonsterRefCfg.h"
#include "Common/TableData/ChoiceChoiceCfg.h"
#include "Common/CampDefine.h"

void MissionPart::DecodeSave(MAPSAVE &mapsave, SET_UINT32 &setChapter)
{
	MAPSAVE::iterator iter = mapsave.begin();
	for (; iter != mapsave.end(); ++iter)
	{
		SaveInfo &info = iter->second;
		uint32_t k = info.k;
		uint32_t v = info.v;
		for (int32_t i = 0; i < 32; ++i)
		{
			if ((v >> i) & 1)
			{
				setChapter.insert(k + i);
			}
		}
	}
}

void MissionPart::EncodeSave(SET_UINT32 &setChapter, MAPSAVE &mapsave)
{
	SET_UINT32::iterator iter = setChapter.begin();
	for (; iter != setChapter.end(); ++iter)
	{
		uint32_t chapter = (*iter);
		SaveInfo info;
		info.Add(chapter);
		MAPSAVE::iterator iterSave = mapsave.find(info.k);
		if (iterSave != mapsave.end())
		{
			iterSave->second.Add(chapter);
		}
		else
		{
			mapsave[info.k] = info;
		}
	}
}


MissionPart::MissionPart()
{

	memset(_aryDyIdAlloc, 0, sizeof(_aryDyIdAlloc));
	_playerTrackMissionMap.clear();
	_setSubmitChapter.clear();
	_mapDyCompleteCount.clear();
	_mapDyFreshtime.clear();
	_mapCampCanAccept.clear();
	_mapBountyCanAccept.clear();
	_bountyFreeNum = 0;
	_mapMissionAllDrop.clear();
	_mapMissionOpen.clear();
	_eventTabal.clear();
	_campBoxProgress = 0;
	_campExtraceTimes = 1;
	_bountyAccetpNum = 0;
	_lastCheckTimeout = g_GetGlobalServerTime()->Tick();
}

MissionPart::~MissionPart()
{
}

bool MissionPart::SaveDB(CharacterDBInfo& characterDB)
{
	ProtoBuf::CharacterDBTaskData* pTaskData = characterDB.mutable_taskdata();
	pTaskData->Clear();


	MAPSAVE mapSave;
	mapSave.clear();
	EncodeSave(_setSubmitChapter, mapSave);
	MAPSAVE::iterator iterSave = mapSave.begin();
	for (; iterSave != mapSave.end(); ++iterSave)
	{
		SaveInfo &info = iterSave->second;
		CharacterDBSubmittedChapter *proto = pTaskData->add_submitchapter();
		if (nullptr != proto)
		{
			proto->set_key(info.k);
			proto->set_val(info.v);
		}
	}
	//
	RecentSubmitTrunkList::iterator iterTrunk = _lstRecentSubmit.begin();
	for (; iterTrunk != _lstRecentSubmit.end(); ++iterTrunk)
	{
		RecentSubmitTrunk &submit = (*iterTrunk);
		CharacterDBSubmittedTrunk *protoTrunk = pTaskData->add_submit_trunk();
		if (nullptr != protoTrunk)
		{
			protoTrunk->set_mission(submit.missionId);
			protoTrunk->set_camp(submit.camp);
			protoTrunk->set_race(submit.race);
		}
	}
	//动态任务数据
	PlayerDyMissionTrackMap::iterator iterDy = _mapDyMissionTrack.begin();
	for (; iterDy != _mapDyMissionTrack.end(); ++iterDy)
	{
		DyMissionTrack &info = iterDy->second;
		CharacterDBDyMissionInfo *proto = pTaskData->add_dyinfo();
		if (nullptr != proto)
		{
			proto->set_mission_type(info.kind);
			proto->set_count(info.finishNum);
			proto->set_lastfresh(info.lastFresh);
		}
	}
	//已接任务列表
	::google::protobuf::RepeatedPtrField< ::ProtoBuf::CharacterDBMissionTrack >* pMissionTrack = pTaskData->mutable_missiontrack();
	for (PlayerTrackMissionMap::iterator it = _playerTrackMissionMap.begin(); it != _playerTrackMissionMap.end(); ++it)
	{
		//LogDebugFmtPrint("MissionPart::Save....cid:%lu,dynamicid:%u,missionid:%u ", m_pMaster->GetCid(), it->second->dynamicId, it->second->missionId);
		ProtoBuf::CharacterDBMissionTrack* pSingleMissionTrack = pMissionTrack->Add();
		if (nullptr != pSingleMissionTrack)
		{
			g_GetMissionManager()->SetMissionTrackProto(it->second, *pSingleMissionTrack);
		}
	}
	//阵营任务
	CharacterDBCampMissionInfo* protoCamp = pTaskData->mutable_campmissioninfo();
	if (nullptr != protoCamp)
	{
		protoCamp->set_boxprogress(_campBoxProgress);
		protoCamp->set_campextracttimes(_campExtraceTimes);
		PlayerTrackMissionMap::iterator itercamp = _mapCampCanAccept.begin();
		for (; itercamp != _mapCampCanAccept.end(); ++itercamp)
		{
			MissionTrack *pMissionTrack = itercamp->second;
			if (nullptr != pMissionTrack)
			{
				ProtoBuf::CharacterDBMissionTrack* pSingleMissionTrack = protoCamp->add_campsinglemission();
				if (nullptr != pSingleMissionTrack)
				{
					g_GetMissionManager()->SetMissionTrackProto(pMissionTrack, *pSingleMissionTrack);
				}
			}
		}
	}

	//赏金任务
	CharacterDBBountyMissionInfo *protobounty = pTaskData->mutable_bountymissioninfo();
	if (nullptr != protobounty)
	{
		protobounty->set_bountyfreenum(_bountyFreeNum);
		protobounty->set_bountyacceptnum(_bountyAccetpNum);
		PlayerTrackMissionMap::iterator iterbounty = _mapBountyCanAccept.begin();
		for (; iterbounty != _mapBountyCanAccept.end(); ++iterbounty)
		{
			MissionTrack *pMissionTrack = iterbounty->second;
			if (nullptr != pMissionTrack)
			{
				ProtoBuf::CharacterDBMissionTrack* pSingleMissionTrack = protobounty->add_bountysinglemission();
				if (nullptr != pSingleMissionTrack)
				{
					g_GetMissionManager()->SetMissionTrackProto(pMissionTrack, *pSingleMissionTrack);
				}
			}
		}
	}

	return true;
}

bool MissionPart::Init(Creature *pMaster, uint32_t partType, CharacterDBInfo* pCharacterDB /* = nullptr */)
{
	Part::Init(pMaster, partType);

	//-----------------------------------------------注册全局事件---------------------------------------------------
	//g_GetEvent()->Subscribe(dynamic_cast<IEventExecuteSink*>(this), EVENT_CREATURE_DEAD, m_pMaster->GetCid(), CREATURE_MONSTER, "MissionPart");
	g_GetEvent()->Subscribe(dynamic_cast<IEventExecuteSink*>(this), EVENT_CREATURE_DEAD, m_pMaster->GetCid(), CREATURE_PLAYER, "MissionPart");
	g_GetEvent()->Subscribe(dynamic_cast<IEventExecuteSink*>(this), EVENT_LEVELUP, m_pMaster->GetCid(), CREATURE_PLAYER, "MissionPart");
	g_GetEvent()->Subscribe(dynamic_cast<IEventExecuteSink*>(this), EVENT_CAMP_CHANGE, m_pMaster->GetCid(), CREATURE_PLAYER, "MissionPart");
	g_GetEvent()->Subscribe(dynamic_cast<IEventExecuteSink*>(this), EVENT_PASS_DUPLICATE, m_pMaster->GetCid(), CREATURE_PLAYER, "MissionPart");
	
	g_GetEvent()->Subscribe(dynamic_cast<IEventExecuteSink*>(this), EVENT_GOD_LEVEL, m_pMaster->GetCid(), CREATURE_PLAYER, "MissionPart");
	g_GetEvent()->Subscribe(dynamic_cast<IEventExecuteSink*>(this), EVENT_STONE_INLAY, m_pMaster->GetCid(), CREATURE_PLAYER, "MissionPart");
	g_GetEvent()->Subscribe(dynamic_cast<IEventExecuteSink*>(this), EVENT_ARENA_JOIN, m_pMaster->GetCid(), CREATURE_PLAYER, "MissionPart");
	g_GetEvent()->Subscribe(dynamic_cast<IEventExecuteSink*>(this), EVENT_UNION_FIGHT_UPGRADE, m_pMaster->GetCid(), CREATURE_PLAYER, "MissionPart");
	g_GetEvent()->Subscribe(dynamic_cast<IEventExecuteSink*>(this), EVENT_UNION_BIAOCHE_FINISH, m_pMaster->GetCid(), CREATURE_PLAYER, "MissionPart");
	g_GetEvent()->Subscribe(dynamic_cast<IEventExecuteSink*>(this), EVENT_UNION_RUN_BUSINESS, m_pMaster->GetCid(), CREATURE_PLAYER, "MissionPart");

	g_GetEvent()->Subscribe(dynamic_cast<IEventExecuteSink*>(this), EVENT_RUNE_INLAY, m_pMaster->GetCid(), CREATURE_PLAYER, "MissionPart");
	g_GetEvent()->Subscribe(dynamic_cast<IEventExecuteSink*>(this), EVENT_SKILL_UP, m_pMaster->GetCid(), CREATURE_PLAYER, "MissionPart");
	g_GetEvent()->Subscribe(dynamic_cast<IEventExecuteSink*>(this), EVENT_CLEAR_POING, m_pMaster->GetCid(), CREATURE_PLAYER, "MissionPart");
	
	g_GetEvent()->Subscribe(dynamic_cast<IEventExecuteSink*>(this), EVENT_ITEM_CHANGE, m_pMaster->GetCid(), CREATURE_PLAYER, "MissionPart");
	g_GetEvent()->Subscribe(dynamic_cast<IEventExecuteSink*>(this), EVENT_GUILD_CHANGE, m_pMaster->GetCid(), CREATURE_PLAYER, "MissionPart");
	g_GetEvent()->Subscribe(dynamic_cast<IEventExecuteSink*>(this), EVENT_BUFF_START_BUFF, m_pMaster->GetCid(), CREATURE_PLAYER, "MissionPart");
	g_GetEvent()->Subscribe(dynamic_cast<IEventExecuteSink*>(this), EVENT_ADD_FRIEND, m_pMaster->GetCid(), CREATURE_PLAYER, "MissionPart");
	g_GetEvent()->Subscribe(dynamic_cast<IEventExecuteSink*>(this), EVENT_EQUIP_REFINE, m_pMaster->GetCid(), CREATURE_PLAYER, "MissionPart");
	g_GetEvent()->Subscribe(dynamic_cast<IEventExecuteSink*>(this), EVENT_DEPUTY_COLLECT_OPERATE, m_pMaster->GetCid(), CREATURE_PLAYER, "MissionPart");
	g_GetEvent()->Subscribe(dynamic_cast<IEventExecuteSink*>(this), EVENT_DEPUTY_MAKE_OPERATE, m_pMaster->GetCid(), CREATURE_PLAYER, "MissionPart");
	g_GetEvent()->Subscribe(dynamic_cast<IEventExecuteSink*>(this), EVENT_DEPUTY_FORGE_EQUIP, m_pMaster->GetCid(), CREATURE_PLAYER, "MissionPart");
	g_GetEvent()->Subscribe(dynamic_cast<IEventExecuteSink*>(this), EVENT_PLAYER_USE_MONSTER, m_pMaster->GetCid(), CREATURE_PLAYER, "MissionPart");
	//订阅离开流放之地事件
	const ConstantConstantCfgInfo *pBanishMap = g_GetConstantConstantCfgTable()->GetConstantConstantCfgInfo(EArg_ClearPoint_Jail);
	if (nullptr == pBanishMap)
	{
		MMOLOG_FMT_ERROR("MissionPart::Init....nullptr == pBanishMap....id:%d ", EArg_ClearPoint_Jail);
		return false;
	}
	g_GetEvent()->Subscribe(dynamic_cast<IEventExecuteSink*>(this), EVENT_LEAVE_SCENE, pBanishMap->constantdata, CREATURE_PLAYER, NULL);
	g_GetEvent()->Subscribe(dynamic_cast<IEventExecuteSink*>(this), EVENT_ENTER_SCENE, pBanishMap->constantdata, CREATURE_PLAYER, NULL);
	//--------------------------------------------------------------------------------------------------------------

	//初始化已接任务列表
	for (int32_t i = 0; i < pCharacterDB->taskdata().missiontrack_size(); i++)
	{
		const ProtoBuf::CharacterDBMissionTrack& pCharacterDBMissionTrack = pCharacterDB->taskdata().missiontrack(i);
		MissionTrack* pMissionTrack = g_GetMissionManager()->AllocMissionTrack();
		if (nullptr != pMissionTrack)
		{
			//LogDebugFmtPrint("MissionPart::Init....cid:%lu,dynamicid:%u,missionid:%u ",m_pMaster->GetCid(), pCharacterDBMissionTrack.dynamicid(), pCharacterDBMissionTrack.missionid());
			if (!g_GetMissionManager()->CopyFromMissionProto(pMissionTrack, pCharacterDBMissionTrack))
			{
				g_GetMissionManager()->FreeMissionTrack(pMissionTrack);
				continue;
			}
			uint32_t dynamicId = pMissionTrack->dynamicId;
			_playerTrackMissionMap.insert(std::make_pair(dynamicId, pMissionTrack));
			//任务进度等级
			int32_t progressLev = 1;
			MissionInfo *pMissionInfo = g_GetMissionManager()->GetMissionCfgInfo(pMissionTrack->missionId);
			if (nullptr != pMissionInfo)
			{
				progressLev = pMissionInfo->progressLev;
			}
			//注册事件
			std::vector<ItemInfo>::iterator iter = pMissionTrack->items.begin();
			for (; iter != pMissionTrack->items.end(); ++iter)
			{
				ItemInfo &itemInfo = (*iter);
				//对已接任务注册事件
				int32_t relevent = MISSION_COND_TYPE_TO_EVENT(itemInfo.type);
				RegisterEvent(relevent, dynamicId, progressLev);
			}
			//任务掉落
			g_GetMissionManager()->OnAddMissionDrop(m_pMaster->GetCid(), this, pMissionTrack, progressLev);
			//
			if (ValidDyMissionId(dynamicId))
			{
				_aryDyIdAlloc[dynamicId] = 1;
			}
		}
	}

	//动态任务数据
	int32_t idysize = pCharacterDB->taskdata().dyinfo_size();
	for (int32_t m = 0; m < idysize; ++m)
	{
		const CharacterDBDyMissionInfo &info = pCharacterDB->taskdata().dyinfo(m);
		DyMissionTrack missionTrack;
		missionTrack.kind = info.mission_type();
		missionTrack.finishNum = info.count();
		missionTrack.lastFresh = info.lastfresh();
		_mapDyMissionTrack[missionTrack.kind] = missionTrack;
	}
	//已完成章节
	MAPSAVE mapSave;
	mapSave.clear();
	int32_t ichapter = pCharacterDB->taskdata().submitchapter_size();
	for (int32_t j = 0; j < ichapter; ++j)
	{
		const CharacterDBSubmittedChapter &info = pCharacterDB->taskdata().submitchapter(j);
		SaveInfo save;
		save.k = info.key();
		save.v = info.val();
		mapSave[save.k] = save;
		DecodeSave(mapSave, _setSubmitChapter);
	}
	//最近提交的主线
	int32_t isubmit = pCharacterDB->taskdata().submit_trunk_size();
	for (int32_t h = 0; h < isubmit; ++h)
	{
		const CharacterDBSubmittedTrunk &protoTrunk = pCharacterDB->taskdata().submit_trunk(h);
		UpdateRecentSubmitTrunk(protoTrunk.mission(), protoTrunk.camp(), protoTrunk.race());
	}
	//阵营任务
	const CharacterDBCampMissionInfo &campproto = pCharacterDB->taskdata().campmissioninfo();
	_campBoxProgress = campproto.boxprogress();
	_campExtraceTimes = campproto.campextracttimes();
	int32_t icamp = campproto.campsinglemission_size();
	for (int32_t m = 0; m < icamp; ++m)
	{
		const CharacterDBMissionTrack& singleCampMission = campproto.campsinglemission(m);
		MissionTrack* pMissionTrack = g_GetMissionManager()->AllocMissionTrack();
		if (nullptr != pMissionTrack)
		{
			if (!g_GetMissionManager()->CopyFromMissionProto(pMissionTrack, singleCampMission))
			{
				g_GetMissionManager()->FreeMissionTrack(pMissionTrack);
				continue;
			}
			_mapCampCanAccept.insert(std::make_pair(pMissionTrack->dynamicId, pMissionTrack));
			if (ValidDyMissionId(pMissionTrack->dynamicId))
			{
				_aryDyIdAlloc[pMissionTrack->dynamicId] = 1;
			}
		}
	}

	//赏金任务
	const CharacterDBBountyMissionInfo &bountyproto = pCharacterDB->taskdata().bountymissioninfo();
	_bountyFreeNum = bountyproto.bountyfreenum();
	_bountyAccetpNum = bountyproto.bountyacceptnum();
	int32_t ibounty = bountyproto.bountysinglemission_size();
	for (int32_t n = 0; n < ibounty; ++n)
	{
		const CharacterDBMissionTrack singleBounty = bountyproto.bountysinglemission(n);
		MissionTrack* pMissionTrack = g_GetMissionManager()->AllocMissionTrack();
		if (nullptr != pMissionTrack)
		{

			if (!g_GetMissionManager()->CopyFromMissionProto(pMissionTrack, singleBounty))
			{
				g_GetMissionManager()->FreeMissionTrack(pMissionTrack);
				continue;
			}
			_mapBountyCanAccept.insert(std::make_pair(pMissionTrack->dynamicId, pMissionTrack));
			if (ValidDyMissionId(pMissionTrack->dynamicId))
			{
				_aryDyIdAlloc[pMissionTrack->dynamicId] = 1;
			}			
		}
	}

	//检查任务刷新
	CheckMissionFresh();
	//检查任务超时
	CheckMissionTimeout(false);
	//设置初始超时时间
	_lastCheckTimeout = g_GetGlobalServerTime()->Tick();
	return true;
}

void MissionPart::OnExecute(uint16_t nEventID, uint64_t nSrcID, uint8_t bySrcType, void *pContext, int32_t nLen)
{
	//走任务内部事件
	switch (nEventID)
	{
	case EVENT_CREATURE_DEAD: //生物死亡
	{
		DieEvent dieEvent = *(DieEvent*)pContext;
		uint32_t monsterId = dieEvent.monsterId;
		if (monsterId > 0) //怪物死亡
		{
			//OnMonsterDie(dieEvent);
		}
		else //角色死亡
		{
			OnDie();
		}
		break;
	}
	case EVENT_LEVELUP:
	{
		OnLevelUp();
		break;
	}
	case EVENT_CAMP_CHANGE:
	{
		OnCampChange();
		break;
	}
	case EVENT_PASS_DUPLICATE:
	{
		OnPassDuplicate(pContext);
		break;
	}
	case EVENT_GOD_LEVEL:
	{
		OnGodLevelUp(pContext);
		break;
	}
	case EVENT_STONE_INLAY:
	{
		OnStoneInlay(pContext);
		break;
	}
	case EVENT_EQUIP_REFINE:
	{
		OnEquipReFine(pContext);
		break;
	}
	case EVENT_RUNE_INLAY:
	{
		OnRuneInlay(pContext);
		break;
	}
	case EVENT_ARENA_JOIN:
	{
		OnEnterArena(pContext);
		break;
	}
	case EVENT_UNION_FIGHT_UPGRADE:
	{
		OnGuildFightLevel(pContext);
		break;
	}
	case EVENT_UNION_BIAOCHE_FINISH: //押镖
	{
		OnGuildEscortFinish(pContext);
		break;
	}
	case EVENT_UNION_RUN_BUSINESS: //跑商
	{
		OnGuildRunBusiness(pContext);
		break;
	}
	case EVENT_DEPUTY_COLLECT_OPERATE:
	{
		OnDeputyCollect(pContext);
		break;
	}
	case EVENT_DEPUTY_MAKE_OPERATE:
	{
		OnDeputyMake(pContext);
		break;
	}
	case EVENT_DEPUTY_FORGE_EQUIP:
	{
		OnDeputyForge(pContext);
		break;
	}
	case EVENT_ITEM_CHANGE:
	{
		OnItemChange(pContext);
		break;
	}
	case EVENT_GUILD_CHANGE:
	{
		CheckMissionOpen(MISSION_TYPE_ID_GUILD);
		CheckMissionOpen(MISSION_TYPE_ID_GUILD_DAILY);
		CheckGuildMission(true);
		CheckGuildDailyMission(true);
		OnGuildChange(pContext);
		break;
	}
	case EVENT_BUFF_START_BUFF:
	{
		OnAddBuff(pContext);
		break;
	}
	case EVENT_ADD_FRIEND:
	{
		OnAddFriend();
		break;
	}
	case EVENT_PLAYER_USE_MONSTER:
	{
		OnUseThingFinish(pContext);
		break;
	}
	case EVENT_LEAVE_SCENE:
	{
		OnLeaveBanishMap(pContext);
		break;
	}
	case EVENT_ENTER_SCENE:
	{
		OnEnterBanishMap(pContext);
		break;
	}
	case EVENT_SKILL_UP:
	{
		OnSkillLevel(pContext);
		break;
	}
	case EVENT_CLEAR_POING:
	{
		OnClearAttrPoint(pContext);
		break;
	}
	default:
		break;
	}

}

bool MissionPart::SynOnLogin()
{
	OnLogin();

	return true;
}

void MissionPart::SynLogout()
{
}

//生物切换逻辑节点
void MissionPart::OnChangeLogic()
{
	//切换逻辑节点之后，可接列表为空了，重新计算出可接列表
	OnLogin();
}

//登录的处理
void MissionPart::OnLogin()
{
	//检查所有任务开启
	CheckAllMissionOpen();
	//检查阵营任务
	CheckCampMission(false,false);
	//检查工会任务
	CheckGuildMission();
	//检查工会日常任务
	CheckGuildDailyMission();
	//检查活动任务
	CheckActCollectMission();
	//检查流放之地任务
	CheckBanishMission();
	//检查主线任务
	CheckTrunkMission(false);

}

void MissionPart::CheckMissionOpen(int32_t missionType)
{
	bool openFlag = false;
	int32_t level = m_pMaster->GetAttr(C_LEVEL);
	const TasktypeTasktypeCfgInfo *pTaskTypeCfg = g_GetTasktypeTasktypeCfgTable()->GetTasktypeTasktypeCfgInfo(missionType);
	if (nullptr != pTaskTypeCfg && level >= pTaskTypeCfg->minlv)
	{
		//流放之地任务需要校验下地图
		if (MISSION_TYPE_ID_GUILD_DAILY == pTaskTypeCfg->tasktypeID)
		{
			const ConstantConstantCfgInfo *pBanishMap = g_GetConstantConstantCfgTable()->GetConstantConstantCfgInfo(EArg_ClearPoint_Jail);
			if (nullptr != pBanishMap && (uint32_t)pBanishMap->constantdata == m_pMaster->GetMapId())
			{
				openFlag = true;
			}
		}

		if (MISSION_OPEN_TYPE_CAMP == pTaskTypeCfg->receiveCondition)
		{
			if (m_pMaster->GetAttr(C_CAMP_ID) > 0)
			{
				openFlag = true;
			}
		}
		else if (MISSION_OPEN_TYPE_UNION == pTaskTypeCfg->receiveCondition)
		{
			if (m_pMaster->GetAttr(C_UNION_ID) > 0)
			{
				openFlag = true;
			}
		}
		else if (MISSION_OPEN_TYPE_ACT == pTaskTypeCfg->receiveCondition)
		{
			if (g_GetGActivityMgr()->IsRunning(pTaskTypeCfg->activityID))
			{
				openFlag = true;
			}
		}
		else
		{
			openFlag = true;
		}
	}
	//
	SetMissionOpen(missionType, openFlag);
}
void MissionPart::CheckAllMissionOpen()
{
	//检查所有类型任务开启
	const SET_INT32 &setAll = g_GetMissionManager()->AllMissionType();
	SET_INT32::const_iterator iterAll = setAll.begin();
	for (; iterAll != setAll.end(); ++iterAll)
	{
		const int32_t missionType = (*iterAll);
		CheckMissionOpen(missionType);
	}
}

void MissionPart::UpdateRecentSubmitTrunk(uint32_t missionId, int32_t camp, int32_t race)//更新最近提交的主线任务
{
	RecentSubmitTrunkList::iterator iter = _lstRecentSubmit.begin();
	for (; iter != _lstRecentSubmit.end(); ++iter)
	{
		RecentSubmitTrunk &submit = (*iter);
		if (submit.camp == camp && submit.race == race)
		{
			submit.missionId = missionId;
			return;
		}
	}
	RecentSubmitTrunk recentSubmit;
	recentSubmit.camp = camp;
	recentSubmit.race = race;
	recentSubmit.missionId = missionId;
	_lstRecentSubmit.push_back(recentSubmit);
}

uint32_t MissionPart::GetRecentSubmitTrunk(int32_t camp, int32_t race) //获取最近提交的主线任务
{
	RecentSubmitTrunkList::iterator iter = _lstRecentSubmit.begin();
	for (; iter != _lstRecentSubmit.end(); ++iter)
	{
		RecentSubmitTrunk &submit = (*iter);
		if (submit.camp == camp && submit.race == race)
		{
			return submit.missionId;
		}
	}
	return 0;
}

void MissionPart::OnLevelUp()
{	

	int32_t level = m_pMaster->GetAttr(C_LEVEL);
	//
	ExecuteData executeData(M_EVENT_LEVEL, level);
	OnEvent(M_EVENT_LEVEL, executeData);
	//检查所有任务开启
	CheckAllMissionOpen();
}

void MissionPart::OnCampChange()
{
	//先触发加入阵营事件，有些任务就是加入阵营的完成条件
	if (m_pMaster->GetAttr(C_CAMP_ID) > 0)
	{
		ExecuteData allExecuteData(M_EVENT_JOIN_CAMP, 0, 1);
		OnEvent(M_EVENT_JOIN_CAMP, allExecuteData);
	}
	/*
	阵营更换后，移除原阵营任务，
	并给玩家接取转换阵营后的第一个当前阵营的主线任务，
	如果玩家再将阵营转回时仍然可以继续完成原阵营主线任务，
	所有原阵营支线任务的完成状态全部清除	
	*/
	ClearMissionByCampChange(true);
	//检查阵营任务开启
	CheckMissionOpen(MISSION_TYPE_ID_CAMP);
	//检查阵营任务
	CheckCampMission(true,true);
	//检查阵营主线
	CheckTrunkMission();
}

void MissionPart::OnPassDuplicate(void* pContext)
{
	PassDupEvent passDupEvent = *(PassDupEvent*)pContext;
	uint32_t dupId = passDupEvent.dupId;
	ExecuteData executeData(M_EVENT_PASS_DUPLICATE, dupId, 1);
	OnEvent(M_EVENT_PASS_DUPLICATE, executeData);
}

void MissionPart::OnGodLevelUp(void* pContext)
{
	GodLevelEvent godLevUp = *(GodLevelEvent*)pContext;
	//神格升级前端显示   5/10 的形式，所以进度需要每次增加 1
	ExecuteData executeData(M_EVENT_GOD_LEVEL, godLevUp.godID,1);
	OnEvent(M_EVENT_GOD_LEVEL, executeData);

	//再抛出一个任意神格升级事件
	ExecuteData allExecuteData(M_EVENT_ANY_GOD_LEVEL, 0, 1);
	OnEvent(M_EVENT_ANY_GOD_LEVEL, allExecuteData);
}

void MissionPart::OnStoneInlay(void* pContext)
{
	//StoneInlayEvent stoneInlay = *(StoneInlayEvent*)pContext;
	ExecuteData allExecuteData(M_EVENT_ANY_STONE_INLAY, 0, 1);
	OnEvent(M_EVENT_ANY_STONE_INLAY, allExecuteData);
}

void MissionPart::OnEquipStren(void* pContext)
{
	/*EquipStrenEvent equipStreanEvent = *(EquipStrenEvent*)pContext;
	uint32_t slot = equipStreanEvent.slot;
	ExecuteData executeData(M_EVENT_UPGRAPE_EQUIP, slot, 1);
	OnEvent(M_EVENT_UPGRAPE_EQUIP, executeData);

	//再抛出一个全身装备强化事件
	ExecuteData allExecuteData(M_EVENT_UPGRAPE_EQUIP, 0, 1);
	OnEvent(M_EVENT_UPGRAPE_EQUIP, allExecuteData);*/
}

void MissionPart::OnEquipReFine(void* pContext)
{
	EquipRefineEvent refineEvent = *(EquipRefineEvent*)pContext;
	uint32_t slot = refineEvent.slot;
	ExecuteData executeData(M_EVENT_REFINE_EQUIP, slot, 1);
	OnEvent(M_EVENT_REFINE_EQUIP, executeData);

	//再抛出一个全身装备精炼事件
	ExecuteData allExecuteData(M_EVNET_ANY_REFINE_EQUIP, 0, 1);
	OnEvent(M_EVNET_ANY_REFINE_EQUIP, allExecuteData);
}

void MissionPart::OnRuneInlay(void* pContext)
{
	RuneInlayEvent runeInlay = *(RuneInlayEvent*)pContext;
	ExecuteData allExecuteData(M_EVEN_RUNE_INLAY, runeInlay.type, 1);
	OnEvent(M_EVEN_RUNE_INLAY, allExecuteData);
}

void MissionPart::OnEnterArena(void *pContext)
{
	//ArenaJoinEvent joinArena = *(ArenaJoinEvent*)pContext;
	ExecuteData allExecuteData(M_EVENT_ARENA, 0, 1);
	OnEvent(M_EVENT_ARENA, allExecuteData);
}

void MissionPart::OnGuildChange(void *pContext)
{
	if (m_pMaster->GetAttr(C_UNION_ID) > 0)
	{
		ExecuteData allExecuteData(M_EVENT_JOIN_GUILD, 0, 1);
		OnEvent(M_EVENT_JOIN_GUILD, allExecuteData);
	}
}

void MissionPart::OnGuildFightLevel(void *pContext)
{
	//UnionFightUpgrade guildFight = *(UnionFightUpgrade*)pContext;
	ExecuteData allExecuteData(M_EVENT_ANY_GUILD_FIGHT_LEVEL, 0, 1);
	OnEvent(M_EVENT_ANY_GUILD_FIGHT_LEVEL, allExecuteData);
}

void MissionPart::OnGuildEscortFinish(void *pContext)
{
	//EscortEvent escortEvent = *(EscortEvent*)pContext;
	ExecuteData allExecuteData(M_EVENT_ANY_ESCORT, 0, 1);
	OnEvent(M_EVENT_ANY_ESCORT, allExecuteData);
}

void MissionPart::OnGuildRunBusiness(void *pContext)
{
	ExecuteData allExecuteData(M_EVENT_ANY_RUN_BUSINESS, 0, 1);
	OnEvent(M_EVENT_ANY_RUN_BUSINESS, allExecuteData);
}

void MissionPart::OnSkillLevel(void *pContext)
{
	playerSkillUpEvent skillEvent = *(playerSkillUpEvent*)pContext;
	ExecuteData allExecuteData(M_EVENT_SKILL_LEVEL, skillEvent.skillID, 1);
	OnEvent(M_EVENT_SKILL_LEVEL, allExecuteData);
}

void MissionPart::OnClearAttrPoint(void *pContext)
{
	//ClearPointEvent attrPoint = *(ClearPointEvent*)pContext;
	ExecuteData allExecuteData(M_EVENT_ATTR_POINT, 0, 1);
	OnEvent(M_EVENT_ATTR_POINT, allExecuteData);
}

void MissionPart::OnDeputyCollect(void* pContext)
{
	CollectOperateEvent collectOperateEvent = *(CollectOperateEvent*)pContext;
	uint32_t type = collectOperateEvent.type;
	ExecuteData executeData(M_EVENT_DEPUTY_COLLECT, type, 1);
	OnEvent(M_EVENT_DEPUTY_COLLECT, executeData);
}

void MissionPart::OnDeputyMake(void* pContext)
{
	MakeOperateEvent makeOperateEvent = *(MakeOperateEvent*)pContext;
	uint32_t type = makeOperateEvent.type;
	ExecuteData executeData(M_EVENT_DEPUTY_MAKE, type, 1);
	OnEvent(M_EVENT_DEPUTY_MAKE, executeData);
}

void MissionPart::OnDeputyForge(void* pContext)
{
	ForgeEquipEvent makeOperateEvent = *(ForgeEquipEvent*)pContext;
	uint32_t type = makeOperateEvent.type;
	ExecuteData executeData(M_EVENT_DEPUTY_MAKE, type, 1);
	OnEvent(M_EVENT_DEPUTY_MAKE, executeData);
}

void MissionPart::OnItemChange(void* pContext)
{
	ItemChangeEvent itemChangeEvent = *(ItemChangeEvent*)pContext;
	uint32_t itemId = itemChangeEvent.itemId;
	int32_t itemNum = itemChangeEvent.itemNum;
	if (itemNum < 0)
	{
		ExecuteData executeData(M_EVENT_USE_GOODS, itemId, abs(itemNum),0,(int32_t)itemChangeEvent.itemSource.source);
		OnEvent(M_EVENT_USE_GOODS, executeData);
	}
	else
	{
		ExecuteData executeData(M_EVENT_COLL_COLLECT_ITEM, itemId, itemNum);
		OnEvent(M_EVENT_COLL_COLLECT_ITEM, executeData);
	}
}

void MissionPart::OnAddBuff(void* pContext)
{
	StartBuffEvent addBuffEvent = *(StartBuffEvent*)pContext;
	uint32_t buffId = addBuffEvent.buffId;
	ExecuteData executeData(M_EVENT_INBUFF, buffId, 1);
	OnEvent(M_EVENT_INBUFF, executeData);
}

void MissionPart::OnAddFriend()
{
	ExecuteData executeData(M_EVENT_ADD_FRIEND, 0, 1);
	OnEvent(M_EVENT_ADD_FRIEND, executeData);
}

void MissionPart::OnUseThingFinish(void* pContext)
{
	UseMonsEvent useEvent = *(UseMonsEvent*)pContext;
	ExecuteData executeData(E_EVENT_USETHING_FINISH, useEvent.monsId, 1);
	OnEvent(E_EVENT_USETHING_FINISH, executeData);
}

void MissionPart::OnLeaveBanishMap(void* pContext)
{
	LeaveSceneEvent *pLeaveEvent = (LeaveSceneEvent*)pContext;
	if (nullptr != pLeaveEvent && pLeaveEvent->cId == m_pMaster->GetCid())
	{
		ClearMissionByType(MISSION_TYPE_ID_BANISH,true);
	}	
}

void MissionPart::OnEnterBanishMap(void *pContext)
{
	EnterSceneEvent *pEnterEvent = (EnterSceneEvent*)pContext;
	if (nullptr != pEnterEvent && pEnterEvent->cId == m_pMaster->GetCid())
	{
		SetMissionOpen(MISSION_TYPE_ID_BANISH, true);
	}
}

bool MissionPart::DailyUpdate(uint64_t unixSec)
{
	CheckMissionFresh();
	LogInfoFmtPrint("[logic] MissionPart::DailyUpdate....");
	return true;
}

bool MissionPart::WeekUpdate(uint64_t unixSec)
{
	CheckMissionFresh();
	LogInfoFmtPrint("[logic] MissionPart::WeekUpdate....");
	return true;
}

void MissionPart::OnDie()
{
	/*//角色死亡需要通知到某些任务失败
	Player* pPlayer = dynamic_cast<Player*>(m_pMaster);

	ProtoBuf::GCDeleteMissionNotify delnotify;
	for (Set::const_iterator i = _dieList.begin(); i != _dieList.end(); ++i)
	{
		uint32_t missionId = *i;
		PlayerTrackMissionMap::iterator ite = _playerTrackMissionMap.find(missionId);
		if (ite != _playerTrackMissionMap.end() && MISSION_E_SUBMITTED > ite->second->status)
		{
			ite->second->status = MISSION_E_FAILURE;
			delnotify.add_missionid(missionId);
			MissionEntry* pMissionEntry = g_GetMissionManager()->GetMissionEntry(missionId);
			if (nullptr != pMissionEntry)
			{
				AbandonUnit abandonUnit;
				abandonUnit.abandonType = M_ABANDON_TYPE_SYS;
				abandonUnit.missionId = missionId;
				pMissionEntry->OnAbandon(pPlayer, abandonUnit);
				g_GetMissionManager()->FreeMissionTrack(ite->second); //释放内存
				_playerTrackMissionMap.erase(ite);
			}
		}

	}
	_dieList.clear();
	m_pMaster->SendDataToClientEx(EMODULE_ID_TASK, LOGIC_TO_CLIENT_GCDELETEMISSIONNOTIFY, &delnotify);*/
}

void MissionPart::OnMonsterDie(DieEvent& dieEvent)
{
	if (dieEvent.killerCid != m_pMaster->GetCid())
	{
		return;
	}
	CharIDType selfCid = m_pMaster->GetCid();
	ExecuteData executeData;
	executeData.type = M_EVENT_KILL_MONSTER;
	executeData.id = dieEvent.monsterId;
	executeData.count = dieEvent.count;
	executeData.killer = dieEvent.killerCid;
	OnEvent(M_EVENT_KILL_MONSTER, executeData);

	Scene *pScene = m_pMaster->GetScene();
	if (nullptr != pScene)
	{
		Monster *pMonster = pScene->GetMonster(dieEvent.nCid);
		if (nullptr != pMonster)
		{
			Point3<float> pos = pMonster->GetPos();
			//统计仇恨列表和归属列表中组队的玩家，可能会有重复部分
			SET_UINT64 setTarget;
			setTarget.clear();
			//
			VEC_UINT64::iterator iterHate = dieEvent.hateTargetList.begin();
			for (; iterHate != dieEvent.hateTargetList.end(); ++iterHate)
			{
				setTarget.insert((*iterHate));
			}
			ORDER_MAP_UINT32_VEC_UINT64::iterator iterTeam = dieEvent.mapTargetTeamMem.begin();
			for (; iterTeam != dieEvent.mapTargetTeamMem.end(); ++iterTeam)
			{
				VEC_UINT64 &vecMem = iterTeam->second;
				VEC_UINT64::iterator iterMem = vecMem.begin();
				for (; iterMem != vecMem.end(); ++iterMem)
				{
					setTarget.insert((*iterMem));
				}
			}
			//任务杀怪计数
			SET_UINT64::iterator iterTarget = setTarget.begin();
			for (; iterTarget != setTarget.end(); ++iterTarget)
			{
				CharIDType shareCid = (*iterTarget);
				//过滤自己
				if (selfCid == shareCid)
				{
					continue;
				}
				Player* pPlayer = g_GetCreatureMgr()->GetPlayer(shareCid);
				if (nullptr != pPlayer)
				{
					MissionPart* pOtherMissionPart = dynamic_cast<MissionPart*>(pPlayer->GetPart(PART_MISSION));
					if (nullptr != pOtherMissionPart)
					{
						pOtherMissionPart->ShareMissionDropByKillMons(dieEvent.monsterId, pMonster->GetAttr(C_LEVEL), dieEvent.count, pos);
					}
				}
			}
		}
	}
}

bool MissionPart::UnInit()
{
	g_GetTimerAxis()->KillAllFixTimer(this);
	g_GetEvent()->UnSubscribeAll(this);
	//释放已接的任务列表
	for (PlayerTrackMissionMap::iterator it = _playerTrackMissionMap.begin(); it != _playerTrackMissionMap.end(); ++it)
	{
		MissionTrack* pMissionTrack = it->second;
		if (nullptr != pMissionTrack)
		{
			g_GetMissionManager()->FreeMissionTrack(pMissionTrack);
		}
	}
	//释放阵营可接任务列表
	for (PlayerTrackMissionMap::iterator itA = _mapCampCanAccept.begin(); itA != _mapCampCanAccept.end(); ++itA)
	{
		MissionTrack* pMissionTrack = itA->second;
		if (nullptr != pMissionTrack)
		{
			g_GetMissionManager()->FreeMissionTrack(pMissionTrack);
		}
	}
	//释放赏金可接任务列表
	for (PlayerTrackMissionMap::iterator itB = _mapBountyCanAccept.begin(); itB != _mapBountyCanAccept.end(); ++itB)
	{
		MissionTrack* pMissionTrack = itB->second;
		if (nullptr != pMissionTrack)
		{
			g_GetMissionManager()->FreeMissionTrack(pMissionTrack);
		}
	}

	_playerTrackMissionMap.clear();
	_mapCampCanAccept.clear();
	_mapBountyCanAccept.clear();
	memset(_aryDyIdAlloc, 0, sizeof(_aryDyIdAlloc));
	_setSubmitChapter.clear();
	_mapDyCompleteCount.clear();
	_mapDyFreshtime.clear();
	_bountyFreeNum = 0;
	_mapMissionAllDrop.clear();
	_eventTabal.clear();
	_bountyAccetpNum = 0;

	return true;
}

void MissionPart::Update(uint64_t tick)
{
	if (tick - _lastCheckTimeout >= 1000)//每1s检测一次
	{
		CheckMissionTimeout();
		_lastCheckTimeout = tick;
	}
}

bool MissionPart::OnMsgHandle(uint32_t cmd, const char* data, uint32_t len)
{
	switch (cmd)
	{
	case CLIENT_TO_LOGIC_QUERY_MiSSIONLIST://任务列表
	{
		SendMissionList(data, len);
		break;
	}
	case CLIENT_TO_LOGIC_NPC_ACCEPTMISSION: //NPC接取任务
	{
		HandleNpcAcceptMission(data, len);
		break;
	}
	case CLIENT_TO_LOGIC_ABANDONMISSION://放弃任务
	{
		HandleAbandonMission(data, len);
		break;
	}
	case CLIENT_TO_LOGIC_SUBMITMISSION: //提交任务
	{
		HandleSubmitMission(data, len);
		break;
	}
	case CLIENT_TO_LOGIC_TALKWITHNPC: //NPC对话
	{
		HandleTalkWithNpc(data, len);
		break;
	}
	case CLIENT_TO_LOGIC_MISSIONANSWER: //任务答题
	{
		HandleMissionAnswer(data, len);
		break;
	}
	case CLIENT_TO_LOGIC_SUBMITMISSIONGOODS: //提交物品
	{
		HandleSubmitMissionGoods(data, len);
		break;
	}
	case CLIENT_TO_LOGIC_GETCAMPMISSIONINFO: //获取阵营任务信息
	{
		HandleGetCampMissionInfo(data, len);
		break;
	}
	case CLIENT_TO_LOGIC_DICECAMPMISSION: //摇骰子
	{
		HandleDiceCampMission(data, len);
		break;
	}
	case CLIENT_TO_LOGIC_GETCAMPBOXREWARD: //领取阵营宝箱
	{
		HandleGetCampBoxReward(data, len);
		break;
	}
	
	case CLIENT_TO_LOGIC_GETBOUNTYMISSIONINFO: //获取赏金任务信息
	{
		HandleGetBountyMissionInfo(data, len);
		break;
	}
	case CLIENT_TO_LOGIC_REFRESHBOUNTYMISSION:	//刷新赏金任务
	{
		HandleUpdateBountyMissionInfo(data, len);
		break;
	}
	case CLIENT_TO_LOGIC_REFRESHGUILDMISSION:	//刷新工会任务
	{
		HandleRefreshGuildMission(data, len);
		break;
	}
	case CLIENT_TO_LOGIC_MISSION_SELECT:	//分支任务选择
	{
		HandleSelMission(data, len);
		break;
	}
	default:
		break;
	}
	return true;
}

void MissionPart::SendMissionList(const char* data, uint32_t len)
{
	ProtoBuf::CGQueryMissionListReq req;

	if (!req.ParseFromArray(data, len))
	{
		MMOLOG_FMT_ERROR("[logic] CGQueryMissionListReq parse failed...");
		return;
	}

	ProtoBuf::GCQueryMissionListRsp rsp;

	//先填充已接任务列表
	for (PlayerTrackMissionMap::const_iterator missionIte = _playerTrackMissionMap.begin(); missionIte != _playerTrackMissionMap.end(); ++missionIte)
	{
		//LogDebugFmtPrint("MissionPart::SendMissionList....cid:%lu,dynamicid:%u,missionid:%u ", m_pMaster->GetCid(), missionIte->second->dynamicId, missionIte->second->missionId);
		ProtoBuf::CMissionTrack* missionTrack = rsp.add_acceptedlist();
		if (nullptr != missionTrack)
		{
			g_GetMissionManager()->SetMissionTrackProto(missionIte->second, *missionTrack);
		}
	}

	//已完成章节
	MAPSAVE mapSave;
	mapSave.clear();
	SET_UINT32 setBranchChapter;
	setBranchChapter.clear();
	//客户端只需要已提交的支线章节
	SET_UINT32::iterator iterChapter = _setSubmitChapter.begin();
	for (; iterChapter != _setSubmitChapter.end(); ++iterChapter)
	{
		const MissionChapterInfo *pChapterCfg = g_GetMissionManager()->GetMissionChapterCfgInfo((*iterChapter));
		if (nullptr != pChapterCfg && pChapterCfg->kind != MISSION_TYPE_ID_TRUNK)
		{
			setBranchChapter.insert((*iterChapter));
		}
	}
	EncodeSave(setBranchChapter, mapSave);
	MAPSAVE::iterator iterSave = mapSave.begin();
	for (; iterSave != mapSave.end(); ++iterSave)
	{
		SaveInfo &info = iterSave->second;
		rsp.add_chapter(info.k);
		rsp.add_chapter(info.v);
	}
	//任务周期内已完成次数
	DyMissionCntAllProto *protoFinishCount = rsp.mutable_finish_count();
	PlayerDyMissionTrackMap::iterator iterCnt = _mapDyMissionTrack.begin();
	for (; iterCnt != _mapDyMissionTrack.end(); ++iterCnt)
	{
		DyMissionTrack &info = iterCnt->second;
		if (nullptr != protoFinishCount)
		{
			DyMissionCntProto *proto = protoFinishCount->add_count();
			if (nullptr != proto)
			{
				proto->set_missiontype(info.kind);
				proto->set_count(info.finishNum);
			}
		}
	}

	rsp.set_finishguildtimes(HaveFinishNumByType(MISSION_TYPE_ID_GUILD));
	rsp.set_finishlooptimes(HaveFinishNumByType(MISSION_TYPE_ID_LOOP));
	m_pMaster->SendDataToClientEx(EMODULE_ID_TASK, LOGIC_TO_CLIENT_QUERY_MiSSIONLIST, &rsp);
}

//NPC接取任务
void MissionPart::HandleNpcAcceptMission(const char* data, uint32_t len)
{
	CGNpcAcceptMissionReq req;
	if (!req.ParseFromArray(data, len))
	{
		MMOLOG_FMT_ERROR("[logic] CGNpcAcceptMissionReq parse failed...");
		return;
	}
	CharIDType cid = m_pMaster->GetCid();
	uint32_t npcid = req.npcid();//校验用的，暂时先不校验
	npcid = npcid;
	int32_t missionType = req.missiontype();
	//任务ID（如果是分支任务，代表task.csv中配置ID，如果是赏金任务 代表动态任务ID）
	uint32_t missionId = req.missionid();

	//
	int32_t ret = RET_MISSION_NOT_EXIST;
	//主支线,流放之地
	if (MISSION_TYPE_ID_TRUNK == missionType 
		|| MISSION_TYPE_ID_BRANCH == missionType
		|| MISSION_TYPE_ID_BANISH == missionType
		)
	{
		//每个章节的第一个任务才需要客户端发请求，其他的都是服务器自动接取
		MissionInfo *pMissionInfo = g_GetMissionManager()->GetMissionCfgInfo(missionId);
		if (nullptr == pMissionInfo)
		{
			LogErrFmtPrint("HandleNpcAcceptMission...nullptr == pMissionInfo..cid:%lu,missionid:%u ", cid, missionId);
		}
		else
		{
			const MissionChapterInfo *pChapterCfg = g_GetMissionManager()->GetMissionChapterCfgInfo(pMissionInfo->chapterId);
			if (nullptr == pChapterCfg)
			{
				LogErrFmtPrint("HandleNpcAcceptMission...nullptr == pChapterCfg..cid:%lu,missionid:%u,chapter:%u ", cid, missionId, pMissionInfo->chapterId);
			}
			else if (pChapterCfg->firstMissionId != missionId)
			{
				LogErrFmtPrint("HandleNpcAcceptMission...pChapterCfg->firstMissionId != missionId..cid:%lu,missionid:%u,chapter:%u,firstmission:%u ", cid, missionId, pMissionInfo->chapterId, pChapterCfg->firstMissionId);
			}
			else
			{
				ret = g_GetMissionManager()->OnAccept(dynamic_cast<Player*>(m_pMaster), missionId, true,false);
				if (RET_SUCCESS == ret)
				{
					LogDebugFmtPrint("HandleNpcAcceptMission...cid:%lu,missionid:%u,chapter:%u,camp:%d,race:%d ", m_pMaster->GetCid(), missionId, pMissionInfo->chapterId, (int32_t)m_pMaster->GetAttr(C_CAMP_ID), (int32_t)m_pMaster->GetAttr(C_RACE));
				}
				else
				{
					LogErrFmtPrint("HandleNpcAcceptMission...failed...cid:%lu,missionid:%u,chapter:%u,camp:%d,race:%d,ret:%d ", m_pMaster->GetCid(), missionId, pMissionInfo->chapterId, (int32_t)m_pMaster->GetAttr(C_CAMP_ID), (int32_t)m_pMaster->GetAttr(C_RACE),ret);
				}
			}
		}		
	}
	else if (MISSION_TYPE_ID_BOUNTY == missionType)
	{
		PlayerTrackMissionMap::iterator iterA = _mapBountyCanAccept.find(missionId);
		if (iterA != _mapBountyCanAccept.end())
		{
			ret = g_GetMissionManager()->OnAcceptDy(dynamic_cast<Player*>(m_pMaster), iterA->second, true);
		}
	}
	else if (MISSION_TYPE_ID_CAMP == missionType) //阵营任务接取有专门的协议
	{
		MMOLOG_FMT_ERROR("HandleNpcAcceptMission....mission type error...cid:%lu,missionType:%d ", cid, missionType);
		return;
	}
	else 
	{
		ret = AcceptMissionByType(missionType,true);
		if (RET_SUCCESS != ret)
		{
			MMOLOG_FMT_ERROR("HandleNpcAcceptMission....AcceptMissionByType failed...cid:%lu,missionType:%d,ret:%d ", cid, missionType, ret);
		}
	}

	CGNpcAcceptMissionRsp rsp;
	rsp.set_retcode(ret);
	m_pMaster->SendDataToClient(EMODULE_ID_TASK, LOGIC_TO_CLIENT_NPC_ACCEPTMISSION, &rsp);
}

void MissionPart::HandleAbandonMission(const char* data, uint32_t len)
{
	ProtoBuf::CGAbandonMissionReq req;

	if (!req.ParseFromArray(data, len))
	{
		MMOLOG_FMT_ERROR("[logic] CGAbandonMissionReq parse failed...");
		return;
	}

	ProtoBuf::GCAbandonMissionRsp rsp;
	uint32_t dymissionId = req.dynamicid();
	//
	int32_t ret = RET_MISSION_NOT_EXIST;
	PlayerTrackMissionMap::iterator iter = _playerTrackMissionMap.find(dymissionId);
	if (iter != _playerTrackMissionMap.end())
	{
		uint32_t missionId = iter->second->missionId;
		MissionInfo *pMissionCfgInfo = g_GetMissionManager()->GetMissionCfgInfo(missionId);
		if (nullptr != pMissionCfgInfo)
		{
			//放弃任务，整个目录都放弃
			ret = g_GetMissionManager()->OnAbandon(dynamic_cast<Player*>(m_pMaster), missionId);
		}
		else
		{
			const DyMissionInfo *pDyMissionCfgInfo = g_GetMissionManager()->GetDyMissionCfgInfo(missionId);
			if (nullptr != pDyMissionCfgInfo)
			{
				ret = g_GetMissionManager()->OnAbandonDy(dynamic_cast<Player*>(m_pMaster), dymissionId,true);
			}
		}
	}
	rsp.set_dynamicid(dymissionId);
	rsp.set_ret(ret);

	m_pMaster->SendDataToClientEx(EMODULE_ID_TASK, LOGIC_TO_CLIENT_ABANDONMISSION, &rsp);

}

void MissionPart::HandleSubmitMission(const char* data, uint32_t len)
{
	ProtoBuf::CGSubmitMissionReq req;

	if (!req.ParseFromArray(data, len))
	{
		MMOLOG_FMT_ERROR("[logic] CGSubmitMisionReq parse failed...");
		return;
	}

	ProtoBuf::GCSubmitMissionRsp rsp;

	uint32_t dymissionId = req.dynamicid();
	uint32_t index = req.index();

	//
	MissionInfo *pMissionCfgInfo = nullptr;
	const DyMissionInfo *pDyMissionCfgInfo = nullptr;
	int32_t ret = RET_MISSION_NOT_EXIST;
	PlayerTrackMissionMap::iterator iter = _playerTrackMissionMap.find(dymissionId);
	if (iter != _playerTrackMissionMap.end())
	{
		uint32_t missionId = iter->second->missionId;
		pMissionCfgInfo = g_GetMissionManager()->GetMissionCfgInfo(missionId);
		if (nullptr != pMissionCfgInfo)
		{
			if (g_GetMissionManager()->IsOptionalParentMission(missionId))
			{
				//分支任务的父任务，有专门的协议处理，不是从这里提交的
				ret = RET_FAIL;
				MMOLOG_FMT_ERROR("HandleSubmitMission....g_GetMissionManager()->IsOptionalParentMission....missionid:%u ", missionId);
			}
			else
			{
				ret = g_GetMissionManager()->OnSubmit(dynamic_cast<Player*>(m_pMaster), missionId, index);
			}			
		}
		else
		{
			pDyMissionCfgInfo = g_GetMissionManager()->GetDyMissionCfgInfo(missionId);
			if (nullptr != pDyMissionCfgInfo)
			{
				ret = g_GetMissionManager()->OnSubmitDy(dynamic_cast<Player*>(m_pMaster), dymissionId);
			}
		}
	}

	if (RET_MISSION_NOT_EXIST != ret && RET_SUCCESS != ret)//这里做特殊处理，成功和任务不存在的时候不返回给前端，只有其他错误的时候才返回给前端
	{
		rsp.set_dynamicid(dymissionId);
		rsp.set_ret(ret);
		m_pMaster->SendDataToClientEx(EMODULE_ID_TASK, LOGIC_TO_CLIENT_SUBMITMISSION, &rsp);
	}
}

void MissionPart::HandleTalkWithNpc(const char* data, uint32_t len)
{
	ProtoBuf::CGTalkWithNpcReq req;

	if (!req.ParseFromArray(data, len))
	{
		MMOLOG_FMT_ERROR("[logic] CGTalkWithNpcReq parse failed...");
		return;
	}

	uint32_t dymissionId = req.dynamicid();
	uint64_t itemId = req.npcid();
	uint32_t type = req.type();

	PlayerTrackMissionMap::iterator it = _playerTrackMissionMap.find(dymissionId);
	if (it == _playerTrackMissionMap.end())
	{
		MMOLOG_FMT_ERROR("[logic] CGTalkWithNpcReq but dymissionId = %u not in playerTrackMissionMap...", dymissionId);
		return;
	}
	//只有对话和到达某区域可以通过该协议进行提交
	if (type != MISSION_FINISH_TYPE_KILL_MONS_AREA
		&& type != MISSION_FINISH_TYPE_TAKL
		&& type != MISSION_FINISH_TYPE_AREA
		&& type != MISSION_FINISH_TYPE_FINISH_ACTION
		
		)
	{
		MMOLOG_FMT_ERROR("[logic] CGTalkWithNpcReq...type error... cid:%lu, dymissionId:%u, itemid:%u , type:%d..",m_pMaster->GetCid(), dymissionId, itemId,type);
		return;
	}

	//type = MISSION_COND_TYPE_TO_EVENT(type);
	
	/*if (type != M_EVENT_TALK && type != M_EVENT_AREA_FLAG && type != M_EVENT_ACTION_BUTTON)
	{
		MMOLOG_FMT_ERROR("[logic] CGTalkWithNpcReq but dymissionId = %u, type:%u but type is error...", dymissionId, type);
		return;
	}*/
	//NPC交谈,到达区域，区域使用行为按钮
	uint32_t eventType = MISSION_COND_TYPE_TO_EVENT(type);
	ExecuteData executeData(eventType, itemId, 1);
	OnEvent(eventType, executeData);

	//任务区域刷怪
	OnAreaFreshMonster(dymissionId);
}

void MissionPart::OnAreaFreshMonster(uint32_t dymissionId)
{
	PlayerTrackMissionMap::iterator iterMission = _playerTrackMissionMap.find(dymissionId);
	if (iterMission == _playerTrackMissionMap.end())
	{
		return;
	}
	CharIDType cid = m_pMaster->GetCid();
	uint32_t missionId = iterMission->second->missionId;
	Scene *pScene = m_pMaster->GetScene();
	if (nullptr == pScene)
	{
		MMOLOG_FMT_ERROR("[logic] OnAreaFreshMonster...nullptr == pScene...cid:%lu, dymissionId = %u, missionid:%u,", cid, dymissionId, missionId);
		return;
	}	
	uint32_t mapId = pScene->GetMapId();
	Point3<float> playerPos = m_pMaster->GetPos();
	//如果是 杀怪追踪区域，玩家到达区域，需要在区域刷新怪物
	//MISSION_FINISH_TYPE_KILL_MONS_AREA = 102,		//杀怪追踪区域		格式 102=怪物id=怪物数量=追踪区域id=0=0（仅适用刷出怪物）
	vector<ItemInfo>::const_iterator iterCond = iterMission->second->items.begin();
	for (; iterCond != iterMission->second->items.end(); ++iterCond)
	{
		const ItemInfo &cond = (*iterCond);
		if (MISSION_FINISH_TYPE_KILL_MONS_AREA != cond.type)
		{
			continue;
		}
		if (cond.currentValue >= cond.finalValue)
		{
			continue;
		}
		int32_t condtype = cond.type;
		uint32_t areaId = cond.parma1;
		uint32_t monsId = cond.itemId;
		int32_t monsNum = cond.finalValue - cond.currentValue;
		if (!pScene->InArea(areaId, playerPos)) //玩家没有达到区域
		{
			continue;
		}
		int32_t hasNum = pScene->MonsNumByMasterCid(monsId, m_pMaster->GetCid());
		if (hasNum >= monsNum)
		{
			MMOLOG_FMT_DEBUG("[logic] OnAreaFreshMonster...already has enough mastercid monster...cid:%lu, dymissionId = %u, missionid:%u, condtype:%d,areaid:%u, monsid:%u,mapid:%u,hasNum:%d,monsNUM:%d ", cid, dymissionId, missionId, condtype, areaId, monsId, mapId, hasNum, monsNum);
			continue;
		}
		const AreaAreaCfgInfo *pAreaCfg = g_GetAreaAreaCfgTable()->GetAreaAreaCfgInfo(areaId);
		if (nullptr == pAreaCfg)
		{
			MMOLOG_FMT_ERROR("[logic] OnAreaFreshMonster...can not find area config..cid:%lu, dymissionId = %u, missionid:%u,condtype:%d, areaid:%u ", cid, dymissionId, missionId, condtype, areaId);
			continue;
		}
		if (pAreaCfg->belongToSceneID != (int32_t)mapId)
		{
			MMOLOG_FMT_ERROR("[logic] OnAreaFreshMonster...pAreaCfg->belongToSceneID != m_pMaster->GetMapId()...cid:%lu, dymissionId = %u, missionid:%u, condtype:%d, areaid:%u, mapid:%u, player_mapid:%u ", cid, dymissionId, missionId, condtype, areaId, pAreaCfg->belongToSceneID, mapId);
			continue;
		}		
		int32_t freshNum = monsNum - hasNum;
		Point3<float>dir(0, 0, 1);
		MonsterExtendInfo extendproto;
		extendproto.set_mastercid(m_pMaster->GetCid());
		extendproto.set_level(m_pMaster->GetAttr(C_LEVEL));
		MonsCreateParam createParam;
		createParam.createType = EMonsCreateType_Mission;
		createParam.createTypeVal = missionId;
		for (int32_t i = 0; i < freshNum; ++i)
		{
			Point3<float> monspos = g_GetMapLocationCfg()->RandPosInArea(areaId);
			Monster *pMonster = g_GetCreatureMgr()->CreateMonster(monsId, pScene->GetSceneId(), monspos, createParam, dir, -1, &extendproto, m_pMaster->GetCid());
			if (nullptr == pMonster)
			{
				MMOLOG_FMT_ERROR("[logic] OnAreaFreshMonster...create monster failed...cid:%lu, dymissionId = %u, missionid:%u, condtype:%d,areaid:%u, monsid:%u,mapid:%u,monspos:%f,%f,%f,i:%d ", cid, dymissionId, missionId, condtype, areaId, monsId, mapId, monspos.x, monspos.y, monspos.z, i);
			}
			else
			{
				MMOLOG_FMT_DEBUG("[logic] OnAreaFreshMonster...create monster sucessed...cid:%lu, dymissionId = %u, missionid:%u, condtype:%d,areaid:%u, monsid:%u,mapid:%u,monspos:%f,%f,%f,i:%d ", cid, dymissionId, missionId, condtype, areaId, monsId, mapId, monspos.x, monspos.y, monspos.z, i);
			}
		}
	}
}

//分支选择任务
void MissionPart::HandleSelMission(const char* data, uint32_t len)
{
	CGMissionSelReq req;
	if (!req.ParseFromArray(data, len))
	{
		MMOLOG_FMT_ERROR("[logic] CGMissionSelReq parse failed...");
		return;
	}
	int32_t ret = RET_FAIL;
	uint32_t dymissionId = req.dynamicid();
	int32_t choiceId = req.sel_id();
	PlayerTrackMissionMap::iterator it;
	MissionTrack *pParentMissionTrack = nullptr;
	uint32_t missionId = 0;
	MissionInfo *pMissionCfgInfo = nullptr;
	SET_UINT32 setCurDymission;
	setCurDymission.clear();
	uint32_t sonDyMissionId = 0;
	CGMissionSelRsp rsp;
	vector<ItemInfo>::iterator iterCond;
	PlayerTrackMissionMap::iterator itEx;
	PlayerTrackMissionMap::iterator itA;
	PlayerTrackMissionMap::iterator itCheck;
	bool flag = false;
	const ChoiceChoiceCfgInfo *pChoiceCfg = g_GetChoiceChoiceCfgTable()->GetChoiceChoiceCfgInfo(choiceId);
	if (nullptr == pChoiceCfg)
	{
		MMOLOG_FMT_ERROR("[logic] HandleSelMission...nullptr == pChoiceCfg...cid:%lu, choiceid:%d ",m_pMaster->GetCid(),choiceId);
		goto Exit0;
	}
	it = _playerTrackMissionMap.find(dymissionId);
	if (it == _playerTrackMissionMap.end())
	{
		ret = RET_MISSION_NOT_EXIST;
		MMOLOG_FMT_ERROR("[logic] HandleSelMission.... mission not exists.....cid:%lu, dymissionId:%u, choiceId:%d ", m_pMaster->GetCid(), dymissionId, choiceId);
		goto Exit0;
	}
	pParentMissionTrack = it->second;
	if (nullptr == pParentMissionTrack)
	{
		ret = RET_MISSION_NOT_EXIST;
		MMOLOG_FMT_ERROR("[logic] HandleSelMission.... nullptr == pParentMissionTrack....cid:%lu, dymissionId:%u, choiceId:%d ", m_pMaster->GetCid(), dymissionId,choiceId);
		goto Exit0;
	}
	missionId = pParentMissionTrack->missionId;
	pMissionCfgInfo = g_GetMissionManager()->GetMissionCfgInfo(missionId);
	if (nullptr == pMissionCfgInfo)
	{
		ret = RET_MISSION_NOT_EXIST;
		MMOLOG_FMT_ERROR("[logic] HandleSelMission.... nnullptr == pMissionCfgInfo....cid:%lu, dymissionId:%u, choiceId:%d ", m_pMaster->GetCid(), dymissionId, choiceId);
		goto Exit0;
	}
	iterCond = pParentMissionTrack->items.begin();
	for (; iterCond != pParentMissionTrack->items.end(); ++it)
	{
		ItemInfo &cond = (*iterCond);
		if (MISSION_FINISH_TYPE_OPTION == cond.type)
		{
			flag = true;
			break;
		}
	}
	if (!flag)
	{
		MMOLOG_FMT_ERROR("[logic] HandleSelMission.... mission finish condition is not  option.....cid:%lu, dymissionId:%u,missionId:%u, choiceId:%d ", m_pMaster->GetCid(), dymissionId, missionId, choiceId);
		return;
	}
	if (!g_GetMissionManager()->IsOptionalSonMission(missionId,pChoiceCfg->nexttask))
	{
		MMOLOG_FMT_ERROR("[logic] HandleSelMission.... g_GetMissionManager()->IsOptionalSonMission return false.....cid:%lu, dymissionId:%u,missionId:%u, choiceId:%d,nexttask:%u ", m_pMaster->GetCid(), dymissionId, missionId, choiceId,pChoiceCfg->nexttask);
		goto Exit0;
	}
	//先把分支父任务从已经中移除
	_playerTrackMissionMap.erase(it);
	//统计所有已接任务列表，主要是了过滤出后面接取分支子任务的动态ID
	itEx = _playerTrackMissionMap.begin();
	for (; itEx != _playerTrackMissionMap.end(); ++itEx)
	{
		setCurDymission.insert(itEx->first);
	}
	//然后接取子任务
	ret = g_GetMissionManager()->OnAccept(dynamic_cast<Player*>(m_pMaster), pChoiceCfg->nexttask, false);
	if (RET_SUCCESS != ret)
	{
		//失败了，需要把父任务添加进已接列表
		_playerTrackMissionMap[dymissionId] = pParentMissionTrack;

		MMOLOG_FMT_ERROR("[logic] HandleSelMission.... g_GetMissionManager()->OnAccept failed.....cid:%lu, dymissionId:%u,missionId:%u, choiceId:%d,nexttask:%u,ret:%d ", m_pMaster->GetCid(), dymissionId, missionId, choiceId, pChoiceCfg->nexttask,ret);
		goto Exit0;
	}
	//成功,过滤出新接取的分支子任务
	itA = _playerTrackMissionMap.begin();
	for (; itA != _playerTrackMissionMap.end(); ++itA)
	{
		SET_UINT32::iterator iterFind = setCurDymission.find(itA->first);
		if (iterFind == setCurDymission.end())
		{
			sonDyMissionId = itA->first;
			break;
		}
	}
	//再次校验下是否成功
	itCheck = _playerTrackMissionMap.find(sonDyMissionId);
	if (itCheck == _playerTrackMissionMap.end())
	{
		//失败了，需要把父任务添加进已接列表
		_playerTrackMissionMap[dymissionId] = pParentMissionTrack;
		MMOLOG_FMT_ERROR("[logic] HandleSelMission.... itCheck == _playerTrackMissionMap.end().....cid:%lu, dymissionId:%u,missionId:%u, choiceId:%d,nexttask:%u,sonDyMissionId:%u ", m_pMaster->GetCid(), dymissionId, missionId, choiceId, pChoiceCfg->nexttask, sonDyMissionId);
		goto Exit0;
	}
	//接取子任务成功，先移除父任务
	ret = g_GetMissionManager()->RemoveMission(dynamic_cast<Player*>(m_pMaster), pParentMissionTrack, pMissionCfgInfo);
	if (RET_SUCCESS != ret)
	{
		//移除失败，正常不会失败，这个时候子任务已经接取成功了，需要把分支父任务直接回收
		g_GetMissionManager()->FreeMissionTrack(pParentMissionTrack);
		MMOLOG_FMT_ERROR("[logic] HandleSelMission.... g_GetMissionManager()->RemoveMission failed.....cid:%lu, dymissionId:%u,missionId:%u, choiceId:%d,nexttask:%u,sonDyMissionId:%u,ret:%d ", m_pMaster->GetCid(), dymissionId, missionId, choiceId, pChoiceCfg->nexttask, sonDyMissionId, ret);
		goto Exit0;
	}
	//提交分支父任务
	OnSubmit(missionId, pChoiceCfg->nexttask, pMissionCfgInfo->chapterId, pMissionCfgInfo->kind);
	//更新新接取的分支子任务
	UpdateMissionProgress(sonDyMissionId);
	//
	ret = RET_SUCCESS;

Exit0:
	rsp.set_retcode(ret);
	m_pMaster->SendDataToClientEx(EMODULE_ID_TASK, LOGIC_TO_CLIENT_MISSION_SELECT, &rsp);
}

void MissionPart::HandleGetCampMissionInfo(const char* data, uint32_t len)
{
	ProtoBuf::CGGetCampMissionInfoReq req;

	if (!req.ParseFromArray(data, len))
	{
		MMOLOG_FMT_ERROR("[logic] CGGetCampMissionInfoReq parse failed...");
		return;
	}

	InitCampMission();
}

void MissionPart::HandleDiceCampMission(const char* data, uint32_t len)
{
	ProtoBuf::CGDiceCampMissionReq req;
	ProtoBuf::CGDiceCampMissionRsp rsp;

	if (!req.ParseFromArray(data, len))
	{
		MMOLOG_FMT_ERROR("[logic] CGDiceCampMissionReq parse failed...");
		return;
	}

	bool isNormal = req.isnormal();
	uint32_t dymissionId = req.dynamicid();
	VEC_INT32 ids;
	ids.clear();
	VEC_INT32 threeIds;
	threeIds.clear();
	if (!MissionOpen(MISSION_TYPE_ID_CAMP))
	{
		rsp.set_ret(RET_MISSION_NOT_OPEN_CAMP_MISSION);
		m_pMaster->SendDataToClientEx(EMODULE_ID_TASK, LOGIC_TO_CLIENT_DICECAMPMISSION, &rsp);
		return;
	}
	//检查次数是否足够
	int32_t finishCount = HaveFinishNumByType(MISSION_TYPE_ID_CAMP);
	uint32_t maxTimes = g_GetMissionManager()->GetCampMissionBaseConfig("CampDiceTimes");
	if (finishCount >= (int32_t)maxTimes)
	{
		rsp.set_ret(RET_MISSION_DICE_TIMES_LIMIT);
		m_pMaster->SendDataToClientEx(EMODULE_ID_TASK, LOGIC_TO_CLIENT_DICECAMPMISSION, &rsp);
		return;
	}

	//先检查是否已经接取过了阵营任务了
	PlayerTrackMissionMap::iterator iter = _mapCampCanAccept.begin();
	for (; iter != _mapCampCanAccept.end(); ++iter)
	{
		if (iter->second->status != MISSION_E_ACCEPTABLE)
		{
			rsp.set_ret(RET_MISSION_HAVE_DICE);
			m_pMaster->SendDataToClientEx(EMODULE_ID_TASK, LOGIC_TO_CLIENT_DICECAMPMISSION, &rsp);
			return;
		}
		if (iter->second->quality == MISSION_QUALTTY_BLUE)
		{
			threeIds.push_back(iter->first);
		}
		else
		{
			ids.push_back(iter->first);
		}
	}
	//高级刷新 需要判断钻石
	if (!isNormal)
	{
		//检测客户端提交上来的任务ID是否在阵营任务列表中
		PlayerTrackMissionMap::iterator iterA = _mapCampCanAccept.find(dymissionId);
		if (iterA != _mapCampCanAccept.end())
		{
			int32_t nDiamond = g_GetMissionManager()->GetCampMissionBaseConfig("CampDiceDiamondCost");
			int32_t nTotalDiamond = m_pMaster->GetAttr(C_DIAMOND) + m_pMaster->GetAttr(C_DIAMOND_BIND);
			if (nTotalDiamond < nDiamond)
			{
				//钻石不足RET_GOLD_LACK
				rsp.set_ret(RET_DIAMOND_LACK);
				m_pMaster->SendDataToClientEx(EMODULE_ID_TASK, LOGIC_TO_CLIENT_DICECAMPMISSION, &rsp);
				return;
			}
			//接取任务，接取成功才扣除钻石
			int32_t ret = g_GetMissionManager()->OnAcceptDy(dynamic_cast<Player*>(m_pMaster), iterA->second, true);
			if (RET_SUCCESS != ret)
			{
				rsp.set_ret(ret);
				m_pMaster->SendDataToClientEx(EMODULE_ID_TASK, LOGIC_TO_CLIENT_DICECAMPMISSION, &rsp);
				return;
			}

			//如果足够扣除钻石
			int32_t nHasBindDiamond = m_pMaster->GetAttr(C_DIAMOND_BIND);
			if (nDiamond > nHasBindDiamond)
			{
				nDiamond -= nHasBindDiamond;
				m_pMaster->AddSourceAttr(C_DIAMOND_BIND, -nHasBindDiamond, true, S_MISSION);
			}
			else
			{
				m_pMaster->AddSourceAttr(C_DIAMOND_BIND, -nDiamond, true, S_MISSION);
				nDiamond = 0;
			}

			if (nDiamond > 0)
			{
				int32_t nHasDiamond = m_pMaster->GetAttr(C_DIAMOND);
				if (nHasDiamond >= nDiamond)
				{
					m_pMaster->AddSourceAttr(C_DIAMOND, -nDiamond, true, S_MISSION);
				}
			}
		}
		else
		{
			//任务不存在
			rsp.set_ret(RET_MISSION_NOT_EXIST);
			m_pMaster->SendDataToClientEx(EMODULE_ID_TASK, LOGIC_TO_CLIENT_DICECAMPMISSION, &rsp);
			return;
		}
	}
	else //否则随机一个现有的ID给玩家
	{
		uint32_t probability = g_GetMissionManager()->GetCampMissionBaseConfig("ThreeMissionProbability");
		uint32_t totalProbability = probability * _campExtraceTimes >= 100 ? 100 : probability * _campExtraceTimes;
		uint32_t randomProbability = Random(1, 100);
		if (randomProbability <= totalProbability) //这里命中三皇冠
		{
			uint32_t size = threeIds.size();
			if (size <= 0)
			{
				return;
			}
			uint32_t index = Random(size);
			dymissionId = threeIds[index];
			//_campExtraceTimes = 1;
		}
		else //没有命中三皇冠那么随机其他皇冠的
		{
			uint32_t size = ids.size();
			if (size <= 0)
			{
				return;
			}
			uint32_t index = Random(size);
			dymissionId = ids[index];
			//_campExtraceTimes++;
		}
		PlayerTrackMissionMap::iterator iterB = _mapCampCanAccept.find(dymissionId);
		if (iterB != _mapCampCanAccept.end())
		{
			//接取任务，接取成功才扣除钻石
			int32_t ret = g_GetMissionManager()->OnAcceptDy(dynamic_cast<Player*>(m_pMaster), iterB->second, true);
			if (RET_SUCCESS != ret)
			{
				rsp.set_ret(ret);
				m_pMaster->SendDataToClientEx(EMODULE_ID_TASK, LOGIC_TO_CLIENT_DICECAMPMISSION, &rsp);
				return;
			}
			//成功
			if (randomProbability <= totalProbability) //这里命中三皇冠
			{
				_campExtraceTimes = 1;
			}
			else
			{
				_campExtraceTimes++;
			}
		}
	}

	rsp.set_ret(RET_SUCCESS);
	rsp.set_dynamicid(dymissionId);
	m_pMaster->SendDataToClientEx(EMODULE_ID_TASK, LOGIC_TO_CLIENT_DICECAMPMISSION, &rsp);
}

void MissionPart::HandleGetCampBoxReward(const char* data, uint32_t len)
{
	ProtoBuf::CGGetCampBoxRewardReq req;
	ProtoBuf::CGGetCampBoxRewardRsp rsp;

	if (!req.ParseFromArray(data, len))
	{
		MMOLOG_FMT_ERROR("[logic] CGGetCampBoxRewardReq parse failed...");
		return;
	}

	uint32_t campBoxMaxProgress = g_GetMissionManager()->GetCampMissionBaseConfig("CampBoxMaxProgress");
	if (_campBoxProgress < campBoxMaxProgress)
	{
		rsp.set_ret(RET_MISSION_CAN_NOT_GET_CAMP_REWARD);
		m_pMaster->SendDataToClientEx(EMODULE_ID_TASK, LOGIC_TO_CLIENT_GETCAMPBOXREWARD, &rsp);
		return;
	}

	//领取奖励
	int32_t ret = RET_SUCCESS;
	uint32_t level = m_pMaster->GetAttr(C_LEVEL);
	uint32_t camp = m_pMaster->GetAttr(C_CAMP_ID);
	uint32_t boxId = g_GetMissionManager()->GetCampBoxId(level, camp);
	if (boxId > 0)
	{
		VEC_INT32 vecBox;
		vecBox.clear();
		vecBox.push_back(boxId);
		SItemSourceParam souceParam;
		ret = g_GetDropMgr()->PlayerAddBox(dynamic_cast<Player*>(m_pMaster), vecBox, souceParam);
	}
	if (RET_SUCCESS == ret)
	{
		//成功扣除宝箱进度
		_campBoxProgress -= campBoxMaxProgress;
	}
	
	rsp.set_ret(ret);
	m_pMaster->SendDataToClientEx(EMODULE_ID_TASK, LOGIC_TO_CLIENT_GETCAMPBOXREWARD, &rsp);
}

void MissionPart::HandleMissionAnswer(const char* data, uint32_t len)
{
	ProtoBuf::CGMissionAnswerReq req;
	ProtoBuf::GCMissionAnswerRsp rsp;

	if (!req.ParseFromArray(data, len))
	{
		MMOLOG_FMT_ERROR("[logic] CGMissionAnswerReq parse failed...");
		return;
	}

	VEC_UINT32 answerIds;
	VEC_UINT32 rightIds;
	uint32_t questionId = req.questionid();

	for (int32_t i = 0; i < req.answerids_size(); i++)
	{
		answerIds.push_back(req.answerids(i));
	}

	bool isRight = g_GetAnswerMgr()->Answer(questionId, answerIds, rightIds);

	for (uint32_t i = 0; i < answerIds.size(); i++)
	{
		rsp.add_answerids(answerIds[i]);
	}

	for (uint32_t i = 0; i < rightIds.size(); i++)
	{
		rsp.add_rightids(rightIds[i]);
	}

	rsp.set_questionid(questionId);
	m_pMaster->SendDataToClientEx(EMODULE_ID_TASK, LOGIC_TO_CLIENT_MISSIONANSWER, &rsp);

	if (isRight)
	{
		//回答问题
		ExecuteData executeData(M_EVENT_ANSWER, questionId, 1);
		OnEvent(M_EVENT_ANSWER, executeData);
	}
}

void MissionPart::HandleGetBountyMissionInfo(const char* data, uint32_t len)
{
	ProtoBuf::CGGetBountyMissionInfoReq req;

	if (!req.ParseFromArray(data, len))
	{
		MMOLOG_FMT_ERROR("[logic] CGGetBountyMissionInfoReq parse failed...");
		return;
	}
	if (!MissionOpen(MISSION_TYPE_ID_BOUNTY))
	{
		return;
	}
	uint32_t npcId = req.npcid();
	InitBountyMission(npcId, false);
}

void MissionPart::HandleUpdateBountyMissionInfo(const char* data, uint32_t len)
{
	ProtoBuf::CGRefreshBountyMissionReq req;

	if (!req.ParseFromArray(data, len))
	{
		MMOLOG_FMT_ERROR("[logic] CGRefreshBountyMissionReq parse failed...");
		return;
	}
	if (!MissionOpen(MISSION_TYPE_ID_BOUNTY))
	{
		return;
	}
	uint32_t npcId = req.npcid();
	InitBountyMission(npcId, true);
}

void MissionPart::HandleRefreshGuildMission(const char* data, uint32_t len)
{
	ProtoBuf::CGRefreshGuildMissionReq req;
	ProtoBuf::GCRefreshGuildMissionRsp rsp;

	if (!req.ParseFromArray(data, len))
	{
		MMOLOG_FMT_ERROR("[logic] CGRefreshGuildMissionReq parse failed...");
		return;
	}
	int32_t ret = AcceptMissionByType(MISSION_TYPE_ID_GUILD,true);
	rsp.set_ret(ret);
	m_pMaster->SendDataToClientEx(EMODULE_ID_TASK, LOGIC_TO_CLIENT_REFRESHGUILDMISSION, &rsp);
}

void MissionPart::HandleSubmitMissionGoods(const char* data, uint32_t len)
{
	ProtoBuf::CGSubmitMissionGoodsReq req;
	ProtoBuf::GCSubmitMissionGoodsRsp rsp;

	if (!req.ParseFromArray(data, len))
	{
		MMOLOG_FMT_ERROR("[logic] CGSubmitMissionGoodsReq parse failed...");
		return;
	}
	uint32_t dynamicId = req.dynamicid();
	PlayerTrackMissionMap::iterator iter = _playerTrackMissionMap.find(dynamicId);
	if (iter == _playerTrackMissionMap.end())
	{
		MMOLOG_FMT_ERROR("[logic] CGSubmitMissionGoodsReq iter == _playerTrackMissionMap.end()...cid:%lu,dynamicId:%u ",m_pMaster->GetCid(),dynamicId);
		//
		rsp.set_ret(RET_MISSION_NOT_EXIST);
		m_pMaster->SendDataToClientEx(EMODULE_ID_TASK, LOGIC_TO_CLIENT_SUBMITMISSIONGOODS, &rsp);
		return;
	}
	MissionTrack *pMissionTrack = iter->second;
	if (nullptr == pMissionTrack)
	{
		MMOLOG_FMT_ERROR("[logic] CGSubmitMissionGoodsReq nullptr == pMissionTrack...cid:%lu,dynamicId:%u ", m_pMaster->GetCid(), dynamicId);
		//
		rsp.set_ret(RET_MISSION_NOT_EXIST);
		m_pMaster->SendDataToClientEx(EMODULE_ID_TASK, LOGIC_TO_CLIENT_SUBMITMISSIONGOODS, &rsp);
		return;
	}
	//校验是否是提交物品任务
	bool result = false;
	MAP_UINT32_UINT32 mapSubmitItem;
	mapSubmitItem.clear();
	std::vector<ItemInfo>::iterator iterCond = pMissionTrack->items.begin();
	for (; iterCond != pMissionTrack->items.end(); ++iterCond)
	{
		ItemInfo &cond = (*iterCond);
		if (MISSION_FINISH_TYPE_SUBMIT_ITEM == cond.type || MISSION_FINISH_TYPE_SUBMIT_EQUIP == cond.type)
		{
			result = true;
			MAP_UINT32_UINT32::iterator iterItem = mapSubmitItem.find(cond.itemId);
			if (iterItem != mapSubmitItem.end())
			{
				iterItem->second += cond.finalValue;
			}
			else
			{
				mapSubmitItem[cond.itemId] = cond.finalValue;
			}
		}
	}
	if (!result)
	{
		MMOLOG_FMT_ERROR("[logic] CGSubmitMissionGoodsReq not submit item mission...cid:%lu,dynamicId:%u,missionid:%u ", m_pMaster->GetCid(), dynamicId,pMissionTrack->missionId);
		return;
	}
	//
	Part* pIpackage = m_pMaster->GetPart(PART_PACKAGE);
	if (nullptr == pIpackage)
	{
		rsp.set_ret(RET_FAIL);
		m_pMaster->SendDataToClientEx(EMODULE_ID_TASK, LOGIC_TO_CLIENT_SUBMITMISSIONGOODS, &rsp);
		return;
	}
	MAP_UINT16_INT32 mapIndexItem;
	mapIndexItem.clear();
	for (int32_t i = 0; i < req.infolist_size(); i++)
	{
		uint32_t index = req.infolist(i).index();
		uint32_t goodsNum = req.infolist(i).goodsnum();

		const CItemBase *pItem = pIpackage->GetItem((uint16_t)index);
		if (nullptr == pItem)
		{
			MMOLOG_FMT_ERROR("[logic] CGSubmitMissionGoodsReq nullptr == pItem...cid:%lu,dynamicId:%u,missionid:%u,index:%u,num:%d ", m_pMaster->GetCid(), dynamicId, pMissionTrack->missionId,index,goodsNum);
			return;
		}
		//判断提交的物品是否是任务完成条件需要的物品
		uint32_t itemId = pItem->GetItemID();
		MAP_UINT32_UINT32::iterator iter = mapSubmitItem.find(itemId);
		if (iter == mapSubmitItem.end())
		{
			MMOLOG_FMT_ERROR("[logic] CGSubmitMissionGoodsReq iter == mapSubmitItem.end()...cid:%lu,dynamicId:%u,missionid:%u,index:%u,itemid:%u, num:%d ", m_pMaster->GetCid(), dynamicId, pMissionTrack->missionId, index,itemId, goodsNum);
			return;
		}
		//判断格子物品数量
		uint32_t idxNum = 0;
		MAP_UINT16_INT32::iterator iterIdx = mapIndexItem.find(index);
		if (iterIdx != mapIndexItem.end())
		{
			idxNum = iterIdx->second;
		}

		if (pItem->GetNum() < (goodsNum + idxNum))
		{
			MMOLOG_FMT_ERROR("[logic] CGSubmitMissionGoodsReq pItem->GetNum() < (goodsNum + idxNum)...cid:%lu,dynamicId:%u,missionid:%u,index:%u,itemid:%u,num:%d,hasnum:%u,idxNum:%u ", m_pMaster->GetCid(), dynamicId, pMissionTrack->missionId, index,itemId, goodsNum,pItem->GetNum(),idxNum);
			return;
		}
		//
		if (iterIdx != mapIndexItem.end())
		{
			iterIdx->second += goodsNum;
		}
		else
		{
			mapIndexItem[index] = goodsNum;
		}
	}
	SItemSourceParam sourceParam;
	sourceParam.source = S_Mission_SubmitItem;
	if (!pIpackage->RemoveItem(mapIndexItem, sourceParam))
	{
		rsp.set_ret(RET_PACKAGE_SPACE_NOT_ENOUGH);
		m_pMaster->SendDataToClientEx(EMODULE_ID_TASK, LOGIC_TO_CLIENT_SUBMITMISSIONGOODS, &rsp);
		return;
	}
	rsp.set_ret(RET_SUCCESS);
	m_pMaster->SendDataToClientEx(EMODULE_ID_TASK, LOGIC_TO_CLIENT_SUBMITMISSIONGOODS, &rsp);
}

void MissionPart::InitCampMission(bool bRefresh, bool bNotify)
{
	if (!MissionOpen(MISSION_TYPE_ID_CAMP))
	{
		return;
	}
	//如果可接列表为空，不管当前是否有已接取任务，直接刷新
	if (_mapCampCanAccept.size() <= 0)
	{
		bRefresh = true;
	}
	else
	{
		//当前有已接阵营任务，不刷新
		int32_t haveAccept = MissionNumByType(MISSION_TYPE_ID_CAMP);
		if (haveAccept > 0)
		{
			bRefresh = false;
		}
		else
		{
			//检测是否要重新刷新阵营任务面板
			uint64_t nowTime = Time::Now().sec();
			//上次刷新时间
			uint64_t lastfresh = GetMissionFreshTime(MISSION_TYPE_ID_CAMP);
			//如果不是同一天那么需要做刷新操作
			if (IsNeedFresh(nowTime, MISSION_TYPE_ID_CAMP, lastfresh))
			{
				bRefresh = true;
			}
			else
			{
				//检查下当前玩家等级段是否和可接列表等级段一样，如果不一样，需要刷新
				uint32_t level = m_pMaster->GetAttr(C_LEVEL);
				PlayerTrackMissionMap::iterator iter = _mapCampCanAccept.begin();
				for (; iter != _mapCampCanAccept.end(); ++iter)
				{
					uint32_t missionId = iter->second->missionId;
					const DyMissionInfo *pMissionInfo = g_GetMissionManager()->GetDyMissionCfgInfo(missionId);
					if (nullptr != pMissionInfo
						 && ((level < pMissionInfo->minLev) || (level > pMissionInfo->maxLev))
						)
					{
						bRefresh = true;
						break;
					}
				} // end of for (; iter != _mapCampCanAccept.end(); ++iter)
			}

		}
		
	}


	if (bRefresh)
	{
		uint64_t nowTime = Time::Now().sec();
		int32_t finishNum = HaveFinishNumByType(MISSION_TYPE_ID_CAMP);
		SetDyMissionTrack(MISSION_TYPE_ID_CAMP, finishNum, nowTime);

		//清空工会可接任务列表
		PlayerTrackMissionMap::iterator iterA = _mapCampCanAccept.begin();
		for (; iterA != _mapCampCanAccept.end(); ++iterA)
		{
			FreeDyMissionId(iterA->first);
			g_GetMissionManager()->FreeMissionTrack(iterA->second);
		}
		_mapCampCanAccept.clear();

		//
		int32_t level = m_pMaster->GetAttr(C_LEVEL);
		int32_t camp = m_pMaster->GetAttr(C_CAMP_ID);
		int32_t blueNum = 0;
		int32_t greenNum = 0;
		int32_t whiteNum = 0;
		g_GetMissionManager()->GetCampMissionNumConfig(level, camp, blueNum, greenNum, whiteNum);
		for (int32_t i = 0; i < blueNum; i++)
		{
			MissionTrack *pMissionTrack = g_GetMissionManager()->AllocMissionTrack();
			if (nullptr != pMissionTrack)
			{
				if (RET_SUCCESS == g_GetMissionManager()->DyRandMissionTrackByType(dynamic_cast<Player*>(m_pMaster), MISSION_TYPE_ID_CAMP, pMissionTrack))
				{
					pMissionTrack->quality = MISSION_QUALTTY_BLUE;
					_mapCampCanAccept[pMissionTrack->dynamicId] = pMissionTrack;
				}
				else
				{
					g_GetMissionManager()->FreeMissionTrack(pMissionTrack);
					MMOLOG_FMT_ERROR("InitCampMission....DyRandMissionTrackByType failed...cid:%lu ", m_pMaster->GetCid());
				}
			}
		}
		for (int32_t j = 0; j < greenNum; j++)
		{
			MissionTrack *pMissionTrack = g_GetMissionManager()->AllocMissionTrack();
			if (nullptr != pMissionTrack)
			{
				if (RET_SUCCESS == g_GetMissionManager()->DyRandMissionTrackByType(dynamic_cast<Player*>(m_pMaster), MISSION_TYPE_ID_CAMP, pMissionTrack))
				{
					pMissionTrack->quality = MISSION_QUALTTY_GREEN;
					_mapCampCanAccept[pMissionTrack->dynamicId] = pMissionTrack;
				}
				else
				{
					g_GetMissionManager()->FreeMissionTrack(pMissionTrack);
					MMOLOG_FMT_ERROR("InitCampMission....DyRandMissionTrackByType failed...cid:%lu ", m_pMaster->GetCid());
				}
			}
		}
		for (int32_t k = 0; k < whiteNum; k++)
		{
			MissionTrack *pMissionTrack = g_GetMissionManager()->AllocMissionTrack();
			if (nullptr != pMissionTrack)
			{
				if (RET_SUCCESS == g_GetMissionManager()->DyRandMissionTrackByType(dynamic_cast<Player*>(m_pMaster), MISSION_TYPE_ID_CAMP, pMissionTrack))
				{
					pMissionTrack->quality = MISSION_QUALITY_WRITE;
					_mapCampCanAccept[pMissionTrack->dynamicId] = pMissionTrack;
				}
				else
				{
					g_GetMissionManager()->FreeMissionTrack(pMissionTrack);
					MMOLOG_FMT_ERROR("InitCampMission....DyRandMissionTrackByType failed...cid:%lu ", m_pMaster->GetCid());
				}
			}
		}
	}
	
	//返回阵营任务给客户端
	if (bNotify)
	{
		//填充阵营任务信息
		ProtoBuf::GCGetCampMissionInfoRsp rsp;
		rsp.set_times(HaveFinishNumByType(MISSION_TYPE_ID_CAMP));
		rsp.set_boxporgress(_campBoxProgress);
		//
		PlayerTrackMissionMap::iterator iterMission = _mapCampCanAccept.begin();
		for (; iterMission != _mapCampCanAccept.end(); ++iterMission)
		{
			CMissionTrack *proto = rsp.add_missioninfolist();
			if (nullptr != proto)
			{
				g_GetMissionManager()->SetMissionTrackProto(iterMission->second, *proto);
			}
		}

		m_pMaster->SendDataToClientEx(EMODULE_ID_TASK, LOGIC_TO_CLIENT_GETCAMPMISSIONINFO, &rsp);
	}
}

void MissionPart::ClearMissionByCampChange(bool notify) //通过改变阵营清除任务
{
	//改变阵营，清空所有的动态任务，主支线清空所有阵营相关的任务
	CharIDType cid = m_pMaster->GetCid();
	MAP_UINT32_UINT32 mapDelMission;
	mapDelMission.clear();
	MAP_UINT32_UINT32 mapDelMissionEx;
	mapDelMissionEx.clear();
	SET_UINT32 setDelChater;
	setDelChater.clear();
	PlayerTrackMissionMap::iterator iter = _playerTrackMissionMap.begin();
	for (; iter != _playerTrackMissionMap.end(); ++iter)
	{
		uint32_t missionId = iter->second->missionId;
		uint32_t dymissionId = iter->second->dynamicId;
		const DyMissionInfo *pDyMissionCfgInfo = g_GetMissionManager()->GetDyMissionCfgInfo(missionId);
		if (nullptr != pDyMissionCfgInfo)
		{
			mapDelMission[dymissionId] = missionId;
		}
		else
		{
			MissionInfo *pMissionCfgInfo = g_GetMissionManager()->GetMissionCfgInfo(missionId);
			if (nullptr != pMissionCfgInfo)
			{
				const MissionChapterInfo *pChapterCfg = g_GetMissionManager()->GetMissionChapterCfgInfo(pMissionCfgInfo->chapterId);
				if (nullptr != pChapterCfg)
				{
					if (pChapterCfg->accept.camp > 0)
					{
						mapDelMissionEx[dymissionId] = missionId;
						setDelChater.insert(pChapterCfg->chapterId);
					}
				}
				else
				{
					LogErrFmtPrint("ClearMissionByCampChange..can not find mission chapter cfg...cid:%lu,missionid:%u,chapterid:%u ", cid, missionId, pMissionCfgInfo->chapterId);
				}
			}
		}
	}
	//
	MAP_UINT32_UINT32::iterator iterDel = mapDelMission.begin();
	for (; iterDel != mapDelMission.end(); ++iterDel)
	{
		uint32_t dymissionId = iterDel->first;
		uint32_t missionId = iterDel->second;
		int32_t ret = g_GetMissionManager()->RemoveDyMission(dynamic_cast<Player*>(m_pMaster), dymissionId, notify);
		if (RET_SUCCESS != ret)
		{
			//这里必须打印日志，如果移除失败，很可能导致下面刷新阵营任务分配的动态ID有重复的
			MMOLOG_FMT_ERROR("MissionPart::ClearMissionByCampChange...RemoveDyMission failed....cid:%lu, missionId:%u, dymissionid:%u ", cid, missionId, dymissionId);
		}
	}

	//
	MAP_UINT32_UINT32::iterator iterDelEx = mapDelMissionEx.begin();
	for (; iterDelEx != mapDelMissionEx.end(); ++iterDelEx)
	{
		uint32_t dymissionId = iterDelEx->first;
		uint32_t missionId = iterDelEx->second;
		MissionInfo *pMissionCfgInfo = g_GetMissionManager()->GetMissionCfgInfo(missionId);
		if (nullptr != pMissionCfgInfo)
		{
			int32_t ret = g_GetMissionManager()->RemoveMission(dynamic_cast<Player*>(m_pMaster), pMissionCfgInfo);
			if (RET_SUCCESS != ret)
			{
				MMOLOG_FMT_ERROR("MissionPart::ClearMissionByCampChange...RemoveMission failed....cid:%lu, missionId:%u, dymissionid:%u ", cid, missionId, dymissionId);
			}
		}
		else
		{
			MMOLOG_FMT_ERROR("MissionPart::ClearMissionByCampChange...pMissionCfgInfo is nullptr....cid:%lu, missionId:%u, dymissionid:%u ", cid, missionId, dymissionId);
		}
	}
	//
	SET_UINT32::iterator iterChater = setDelChater.begin();
	for (; iterChater != setDelChater.end(); ++iterChater)
	{
		_setSubmitChapter.erase((*iterChater));
	}
}

void MissionPart::ClearMissionByType(int32_t missionType, bool notify)	//通过任务类型清除任务
{
	CharIDType cid = m_pMaster->GetCid();
	MAP_UINT32_UINT32 mapDelMission;
	mapDelMission.clear();
	MAP_UINT32_UINT32 mapDelMissionEx;
	mapDelMissionEx.clear();
	SET_UINT32 setDelChater;
	setDelChater.clear();
	PlayerTrackMissionMap::iterator iter = _playerTrackMissionMap.begin();
	for (; iter != _playerTrackMissionMap.end(); ++iter)
	{
		uint32_t missionId = iter->second->missionId;
		uint32_t dymissionId = iter->second->dynamicId;
		const DyMissionInfo *pDyMissionCfgInfo = g_GetMissionManager()->GetDyMissionCfgInfo(missionId);
		if (nullptr != pDyMissionCfgInfo)
		{
			if ((uint32_t)missionType == pDyMissionCfgInfo->kind)
			{
				mapDelMission[dymissionId] = missionId;
			}
		}
		else
		{
			MissionInfo *pMissionCfgInfo = g_GetMissionManager()->GetMissionCfgInfo(missionId);
			if (nullptr != pMissionCfgInfo)
			{
				const MissionChapterInfo *pChapterCfg = g_GetMissionManager()->GetMissionChapterCfgInfo(pMissionCfgInfo->chapterId);
				if (nullptr != pChapterCfg)
				{
					if ((uint32_t)missionType == pMissionCfgInfo->kind
						|| (MISSION_TYPE_ID_CAMP == missionType && pChapterCfg->accept.camp > 0)
						)
					{
						mapDelMissionEx[dymissionId] = missionId;
						setDelChater.insert(pChapterCfg->chapterId);
					}
				}
				else
				{
					LogErrFmtPrint("ClearMissionByType..can not find mission chapter cfg...cid:%lu,missionid:%u,chapterid:%u ",cid, missionId, pMissionCfgInfo->chapterId);
				}
			}			
		}
	}
	//
	MAP_UINT32_UINT32::iterator iterDel = mapDelMission.begin();
	for (; iterDel != mapDelMission.end(); ++iterDel)
	{
		uint32_t dymissionId = iterDel->first;
		uint32_t missionId = iterDel->second;
		int32_t ret = g_GetMissionManager()->RemoveDyMission(dynamic_cast<Player*>(m_pMaster), dymissionId, notify);
		if (RET_SUCCESS != ret)
		{
			//这里必须打印日志，如果移除失败，很可能导致下面刷新阵营任务分配的动态ID有重复的
			MMOLOG_FMT_ERROR("MissionPart::ClearMissionByType...RemoveDyMission failed....cid:%lu,missionType:%d, missionId:%u, dymissionid:%u ", cid, missionType, missionId, dymissionId);
		}
	}

	//
	MAP_UINT32_UINT32::iterator iterDelEx = mapDelMissionEx.begin();
	for (; iterDelEx != mapDelMissionEx.end(); ++iterDelEx)
	{
		uint32_t dymissionId = iterDelEx->first;
		uint32_t missionId = iterDelEx->second;
		MissionInfo *pMissionCfgInfo = g_GetMissionManager()->GetMissionCfgInfo(missionId);
		if (nullptr != pMissionCfgInfo)
		{
			int32_t ret = g_GetMissionManager()->RemoveMission(dynamic_cast<Player*>(m_pMaster), pMissionCfgInfo);
			if (RET_SUCCESS != ret)
			{
				MMOLOG_FMT_ERROR("MissionPart::ClearMissionByType...RemoveMission failed....cid:%lu, missionId:%u, dymissionid:%u ", cid, missionId, dymissionId);
			}
		}
		else
		{
			MMOLOG_FMT_ERROR("MissionPart::ClearMissionByType...pMissionCfgInfo is nullptr....cid:%lu, missionId:%u, dymissionid:%u ", cid, missionId, dymissionId);
		}
	}
	//
	SET_UINT32::iterator iterChater = setDelChater.begin();
	for (; iterChater != setDelChater.end(); ++iterChater)
	{
		_setSubmitChapter.erase((*iterChater));
	}
}
//通过活动时间清除任务
void MissionPart::ClearMissionByActTime(int32_t missionType, bool notify)
{
	const TasktypeTasktypeCfgInfo *pTaskTypeCfg = g_GetTasktypeTasktypeCfgTable()->GetTasktypeTasktypeCfgInfo(missionType);
	if (nullptr == pTaskTypeCfg || pTaskTypeCfg->activityID <= 0)
	{
		return;
	}
	const ActData *pActData = g_GetGActivityMgr()->GetActData(pTaskTypeCfg->activityID);
	if (nullptr == pActData)
	{
		return;
	}
	CharIDType cid = m_pMaster->GetCid();
	MAP_UINT32_UINT32 mapDelMission;
	mapDelMission.clear();
	PlayerTrackMissionMap::iterator iter = _playerTrackMissionMap.begin();
	for (; iter != _playerTrackMissionMap.end(); ++iter)
	{
		uint32_t missionId = iter->second->missionId;
		uint32_t dymissionId = iter->second->dynamicId;
		const DyMissionInfo *pDyMissionCfgInfo = g_GetMissionManager()->GetDyMissionCfgInfo(missionId);
		if (nullptr != pDyMissionCfgInfo && (uint32_t)missionType == pDyMissionCfgInfo->kind)
		{
			if (iter->second->acceptMissionTime < pActData->beginTime
				|| iter->second->acceptMissionTime > pActData->endTime
				)
			{
				mapDelMission[dymissionId] = missionId;
			}
		}
	}
	MAP_UINT32_UINT32::iterator iterDel = mapDelMission.begin();
	for (; iterDel != mapDelMission.end(); ++iterDel)
	{
		uint32_t dymissionId = iterDel->first;
		uint32_t missionId = iterDel->second;
		int32_t ret = g_GetMissionManager()->RemoveDyMission(dynamic_cast<Player*>(m_pMaster), dymissionId, notify);
		if (RET_SUCCESS != ret)
		{
			//这里必须打印日志，如果移除失败，很可能导致下面刷新阵营任务分配的动态ID有重复的
			MMOLOG_FMT_ERROR("MissionPart::ClearMissionByActTime...RemoveDyMission failed....cid:%lu,missionType:%d, missionId:%u, dymissionid:%u ", cid, missionType, missionId, dymissionId);
		}
	}

}
//通过任务类型接取任务
int32_t MissionPart::AcceptMissionByType(int32_t missionType, bool notify)
{
	if (!MissionOpen(missionType))
	{
		return RET_MISSION_NOT_OPEN;
	}
	int32_t ret = RET_FAIL;
	int32_t level = m_pMaster->GetAttr(C_LEVEL);
	int32_t maxCount = g_GetMissionManager()->DyMaxCount(missionType, level);
	if (maxCount == MISSION_INFINITE_COUNT
		|| HaveFinishNumByType(missionType) < maxCount
		)
	{
		if (MissionNumByType(missionType) <= 0)
		{
			uint32_t missionId = g_GetMissionManager()->DyRandMissionId(dynamic_cast<Player*>(m_pMaster), missionType);
			const DyMissionInfo *pDyMissionCfgInfo = g_GetMissionManager()->GetDyMissionCfgInfo(missionId);
			if (nullptr == pDyMissionCfgInfo)
			{
				ret = RET_MISSION_NOT_EXIST;
				MMOLOG_FMT_ERROR("AcceptMissionByType...can not find mission config....cid:%lu,missionType:%d, missionid:%u, notify:%d ", m_pMaster->GetCid(), missionType, missionId, (int32_t)notify);
			}
			else
			{
				ret = g_GetMissionManager()->OnAcceptDy(dynamic_cast<Player*>(m_pMaster), missionId, notify);
				if (ret != RET_SUCCESS)
				{
					MMOLOG_FMT_ERROR("AcceptMissionByType...can not find mission config....cid:%lu,missionType:%d, missionid:%u, notify:%d ", m_pMaster->GetCid(), missionType, missionId, (int32_t)notify);
				}
			}
		}
		else
		{
			ret = RET_MISSION_HAVE_TYPE_ACCEPT;
		}
	}
	else
	{
		ret = RET_MISSION_PERIOD_FINISH_NUM_LIMIT;
	}

	return ret;
}

ERetCode MissionPart::InitBountyMission(uint32_t npcId, bool bRefresh)
{
	ProtoBuf::GCGetBountyMissionInfoRsp rsp;
	ERetCode stauts = RET_SUCCESS;
	uint32_t freeFreshNum = g_GetMissionManager()->GetBountyMissionBaseConfig("BountyMissionFreshTimes");
	int32_t costDiamond = g_GetMissionManager()->GetBountyMissionBaseConfig("BountyMissionFreshCost");
	uint32_t cdTime = g_GetMissionManager()->GetBountyMissionBaseConfig("BountyMissionFreshTime");
	int32_t bountyNum = g_GetMissionManager()->GetBountyMissionBaseConfig("BountyMissionNums");
	uint64_t lastfreshTime = GetMissionFreshTime(MISSION_TYPE_ID_BOUNTY);
	int32_t finishNum = HaveFinishNumByType(MISSION_TYPE_ID_BOUNTY);
	uint64_t nowTime = Time::Now().sec();
	int32_t costDiamondEx = costDiamond;
	//检测是否要重新刷新赏金任务面板
	bool needFresh = false;
	if (nowTime >= lastfreshTime + cdTime * 60)
	{
		needFresh = true;
	}
	//
	do 
	{
		//到了刷新时间，或者手动刷新，或者可接列表任务数量未达到制定数量 这些情况都需要刷新
		//刷新时保留可接列表中已经接取的任务，其他任务移除重新刷新
		if (needFresh || bRefresh || (int32_t)_mapBountyCanAccept.size() < bountyNum)
		{
			//需要移除的可接任务
			SET_UINT32 setRemove;
			setRemove.clear();
			//已经接取的赏金任务
			SET_UINT32 setAccept;
			setAccept.clear();
			MissionLstByType(MISSION_TYPE_ID_BOUNTY, setAccept);
			//
			PlayerTrackMissionMap::iterator iterCan = _mapBountyCanAccept.begin();
			while (iterCan != _mapBountyCanAccept.end())
			{
				SET_UINT32::iterator iterAccept = setAccept.find(iterCan->first);
				if (iterAccept == setAccept.end()) //可接列表 没有已经接取的任务都需要移除
				{
					FreeDyMissionId(iterCan->first);
					g_GetMissionManager()->FreeMissionTrack(iterCan->second);
					iterCan = _mapBountyCanAccept.erase(iterCan);
					continue;
				}
				++iterCan;
			}

			//使用钻石立即刷新
			if (bRefresh)
			{
				//所有的赏金任务都在已接取列表，无法刷新任务
				if ((int32_t)_mapBountyCanAccept.size() >= bountyNum)
				{
					stauts = RET_MISSION_ALL_BOUNTY_IN_DOING;
					break;
				}
				//超过最大接取次数之后，不允许手动刷新
				if (_bountyAccetpNum >= g_GetMissionManager()->BountyMaxAcceptNum())
				{
					stauts = RET_MISSION_HAVE_ACCEPT_NUMBER_LIMIT;
					break;					
				}
				//手动刷新消耗顺序：免费次数->刷新道具->绑钻->钻石
				//一天免费3次
				if (_bountyFreeNum >= freeFreshNum)
				{

					Part *pPackage = m_pMaster->GetPart(PART_PACKAGE);
					if (nullptr == pPackage)
					{
						stauts = RET_FAIL;
						break;
					}
					SItemSourceParam sourceParam;
					sourceParam.source = S_MISSION;
					if (!pPackage->RemoveItem(g_GetMissionManager()->BountyFreshItemID(), 1, sourceParam))
					{
						int32_t nTotalDiamond = m_pMaster->GetAttr(C_DIAMOND) + m_pMaster->GetAttr(C_DIAMOND_BIND);
						if (nTotalDiamond < costDiamond)
						{
							stauts = RET_DIAMOND_LACK;
							break;
						}
						//如果足够扣除钻石
						int32_t nHasBindDiamond = (int32_t)m_pMaster->GetAttr(C_DIAMOND_BIND);
						if (costDiamond > nHasBindDiamond)
						{
							costDiamond -= nHasBindDiamond;
							m_pMaster->AddSourceAttr(C_DIAMOND_BIND, -nHasBindDiamond, true, S_MISSION);
							//
							m_pMaster->AddSourceAttr(C_DIAMOND, -costDiamond, true, S_MISSION);
						}
						else
						{
							m_pMaster->AddSourceAttr(C_DIAMOND_BIND, -costDiamond, true, S_MISSION);
						}
					}		
				}
				else
				{
					//增加免费次数
					++_bountyFreeNum;
				}
			}
			else
			{
				//设置刷新时间
				SetDyMissionTrack(MISSION_TYPE_ID_BOUNTY, finishNum, nowTime);
			}
			//
			int32_t loopNum = finishNum + 1;
			int32_t size = bountyNum - _mapBountyCanAccept.size();
			for (int32_t i = 0; i < size; ++i)
			{
				MissionTrack *pMissionTrack = g_GetMissionManager()->AllocMissionTrack();
				if (nullptr != pMissionTrack)
				{
					if (RET_SUCCESS == g_GetMissionManager()->DyRandMissionTrackByType(dynamic_cast<Player*>(m_pMaster), MISSION_TYPE_ID_BOUNTY, pMissionTrack))
					{
						
						g_GetMissionManager()->GetBountyMissionInfo(bRefresh, pMissionTrack, loopNum);
						_mapBountyCanAccept[pMissionTrack->dynamicId] = pMissionTrack;
					}
					else
					{
						g_GetMissionManager()->FreeMissionTrack(pMissionTrack);
						MMOLOG_FMT_ERROR("InitBountyMission....DyRandMissionTrackByType failed...cid:%lu ", m_pMaster->GetCid());
					}
				}
			}

		} // end of if (needFresh || bRefresh || _mapBountyCanAccept.size() < bountyNum)

	} while (0);
	

	rsp.set_retcode(stauts);
	if (RET_SUCCESS == stauts)
	{
		lastfreshTime = GetMissionFreshTime(MISSION_TYPE_ID_BOUNTY);
		rsp.set_freshtimes(_bountyFreeNum);
		rsp.set_freshtime(nowTime >= (lastfreshTime + cdTime * 60) ? 0 : (cdTime * 60 - (nowTime - lastfreshTime)));
		rsp.set_diamondcost(costDiamondEx);
		rsp.set_acceptnum(_bountyAccetpNum);
		PlayerTrackMissionMap::iterator iterC = _mapBountyCanAccept.begin();
		for (; iterC != _mapBountyCanAccept.end(); ++iterC)
		{
			CMissionTrack *proto = rsp.add_missioninfolist();
			if (nullptr != proto)
			{
				g_GetMissionManager()->SetMissionTrackProto(iterC->second, *proto);
			}
			MMOLOG_FMT_DEBUG("[logic] InitBountyMission  dymissionid:%u,  missionid=%u, quality=%d, rewardration=%d, Size=%d, cid:%lu ", iterC->first, iterC->second->missionId, iterC->second->quality, iterC->second->ration, (int32_t)_mapBountyCanAccept.size(), m_pMaster->GetCid());
		}
	}
	
	m_pMaster->SendDataToClientEx(EMODULE_ID_TASK, LOGIC_TO_CLIENT_GETBOUNTYMISSIONINFO, &rsp);

	return stauts;
}

ERetCode MissionPart::CheatAcceptMission(const uint32_t& missionId)
{
	if (nullptr == m_pMaster)
	{
		return RET_FAIL;
	}
	PlayerTrackMissionMap::iterator iter = _playerTrackMissionMap.find(missionId);
	if (iter != _playerTrackMissionMap.end())
	{
		//已经接取，直接返回成功
		return RET_SUCCESS;
	}

	return (ERetCode)g_GetMissionManager()->OnGMAccept(dynamic_cast<Player*>(m_pMaster), missionId, true);
}

ERetCode MissionPart::CheatFastFinishMission(const uint32_t& beginMissionId, const uint32_t& endMissionId)
{
	if (nullptr == m_pMaster)
	{
		return RET_FAIL;
	}

	uint32_t curMissionId = beginMissionId;
	uint32_t count = 0;
	while (count <= 10000)
	{
		MissionInfo * pMissionInfo = g_GetMissionManager()->FindMissionInfoById(curMissionId);
		if (pMissionInfo == NULL)
		{
			return RET_MISSION_NOT_EXIST;
		}
		//快速接取
		int32_t ret = CheatAcceptMission(curMissionId);
		if (RET_SUCCESS != ret)
		{
			return RET_FAIL;
		}
		//快速完成
		ret = CheatFastFinishSigleMission(curMissionId);
		if (RET_SUCCESS != ret)
		{
			return RET_FAIL;
		}
		//快速提交
		ret = CheatSubmitMission(curMissionId);
		if (RET_SUCCESS != ret)
		{
			return RET_FAIL;
		}
		if (curMissionId == endMissionId)
		{
			return RET_SUCCESS;
		}
		//当前任务设置为后置任务
		curMissionId = pMissionInfo->backTaskId;
		//循环次数累加
		++count;
	}

	return RET_SUCCESS;
}

ERetCode MissionPart::CheatFastFinishSigleMission(const uint32_t& missionId, bool notify/* = false*/)
{
	if (nullptr == m_pMaster)
	{
		return RET_FAIL;
	}

	PlayerTrackMissionMap::iterator missionIte = _playerTrackMissionMap.find(missionId);
	if (missionIte == _playerTrackMissionMap.end())
	{
		return RET_MISSION_CAN_NOT_ACCEPT;
	}
	MissionInfo * missionInfo = g_GetMissionManager()->GetMissionCfgInfo(missionId);
	if (nullptr == missionInfo)
	{
		return RET_MISSION_NOT_EXIST;
		/*const DyMissionInfo *pDyMissionInfo = g_GetMissionManager()->GetDyMissionCfgInfo(missionIte->second->missionId);
		if (nullptr == pDyMissionInfo)
		{
			return RET_MISSION_NOT_EXIST;
		}		*/
	}
	if (MISSION_E_COMPLETION == missionIte->second->status)
	{
		//已经完成，直接返回
		return RET_SUCCESS;
	}
	//分支的父任务需要走分支选择协议，会造成任务断层，这里不允许直接完成
	if (g_GetMissionManager()->IsOptionalParentMission(missionId))
	{
		return RET_FAIL;
	}
	//快速完成
	for (std::vector<ItemInfo>::iterator ite = missionIte->second->items.begin(); ite != missionIte->second->items.end(); ++ite)
	{
		ite->currentValue = ite->finalValue;
		ite->completedFlag = true;
	}
	missionIte->second->status = MISSION_E_COMPLETION;

	LogDebugFmtPrint("CheatFastFinishSigleMission...cid:%lu,missionid:%u,chapter:%u,camp:%d,race:%d ", m_pMaster->GetCid(), missionId, missionInfo->chapterId, (int32_t)m_pMaster->GetAttr(C_CAMP_ID), (int32_t)m_pMaster->GetAttr(C_RACE));
	if (notify)
	{
		UpdateMissionProgress(missionId);
	}	

	return RET_SUCCESS;
}

ERetCode MissionPart::CheatRemoveSingleMissiion(const uint32_t& missionId, bool notify/* = true*/)
{
	if (nullptr == m_pMaster)
	{
		return RET_FAIL;
	}

	PlayerTrackMissionMap::iterator missionIte = _playerTrackMissionMap.find(missionId);
	if (missionIte == _playerTrackMissionMap.end())
	{
		return RET_MISSION_CAN_NOT_ACCEPT;
	}
	MissionTrack *pMissionTrack = missionIte->second;
	if (nullptr == pMissionTrack)
	{
		return RET_MISSION_CAN_NOT_ACCEPT;
	}
	MissionInfo *pMissionInfo = g_GetMissionManager()->GetMissionCfgInfo(missionId);
	if (nullptr == pMissionInfo)
	{
		return RET_MISSION_NOT_EXIST;
	}	
	
	_playerTrackMissionMap.erase(missionIte);
	int32_t ret = g_GetMissionManager()->RemoveMission(dynamic_cast<Player*>(m_pMaster), pMissionTrack, pMissionInfo);
	if (RET_SUCCESS != ret)
	{
		_playerTrackMissionMap[pMissionTrack->dynamicId] = pMissionTrack;
	}
	else
	{
		LogDebugFmtPrint("CheatRemoveSingleMissiion...cid:%lu,missionid:%u,chapter:%u,camp:%d,race:%d ", m_pMaster->GetCid(), missionId, pMissionInfo->chapterId, (int32_t)m_pMaster->GetAttr(C_CAMP_ID), (int32_t)m_pMaster->GetAttr(C_RACE));
	}
	return (ERetCode)ret;
}

ERetCode MissionPart::CheatSubmitMission(const uint32_t& missionId)
{
	if (nullptr == m_pMaster)
	{
		return RET_FAIL;
	}
	PlayerTrackMissionMap::iterator missionIte = _playerTrackMissionMap.find(missionId);
	if (missionIte == _playerTrackMissionMap.end())
	{
		return RET_MISSION_CAN_NOT_ACCEPT;
	}

	MissionInfo * missionInfo = g_GetMissionManager()->GetMissionCfgInfo(missionId);
	if (nullptr != missionInfo)
	{
		//随机下 任务随机奖励
		uint32_t selidx = 0;
		if (missionInfo->subAwardRand.size() > 0)
		{
			selidx = Random((uint32_t)missionInfo->subAwardRand.size());
		}
		int32_t ret = g_GetMissionManager()->OnSubmit(dynamic_cast<Player*>(m_pMaster), missionId, selidx);
		if (RET_SUCCESS == ret)
		{
			LogDebugFmtPrint("CheatSubmitMission...cid:%lu,missionid:%u,chapter:%u,camp:%d,race:%d ", m_pMaster->GetCid(), missionId, missionInfo->chapterId, (int32_t)m_pMaster->GetAttr(C_CAMP_ID), (int32_t)m_pMaster->GetAttr(C_RACE));
		}
		return (ERetCode)ret;
	}
	return RET_MISSION_NOT_EXIST;
	/*const DyMissionInfo *pDyMissionInfo = g_GetMissionManager()->GetDyMissionCfgInfo(missionIte->second->missionId);
	if (nullptr == pDyMissionInfo)
	{
		return RET_MISSION_NOT_EXIST;
	}
	return (ERetCode)g_GetMissionManager()->OnSubmitDy(dynamic_cast<Player*>(m_pMaster), missionId);*/
}

////////////////////////////// 新的任务接口 ////////////////////////////////////////////
//更新任务进度
void MissionPart::UpdateMissionProgress(uint32_t missionId)
{
	CharIDType cid = m_pMaster->GetCid();
	PlayerTrackMissionMap::const_iterator missionIte = _playerTrackMissionMap.find(missionId);
	if (missionIte != _playerTrackMissionMap.end())
	{
		ProtoBuf::GCUpdateMissionStatusNotify notify;
		ProtoBuf::CMissionTrack* pMissionTrack = notify.add_updatelist();
		if (nullptr != pMissionTrack)
		{
			g_GetMissionManager()->SetMissionTrackProto(missionIte->second, *pMissionTrack);
			for (uint32_t i = 0; i < missionIte->second->items.size(); i++)
			{
				MMOLOG_FMT_DEBUG("[logic] Update DynamicId=%u,MissionID=%u, MissionType=%u,textid:%u, quality:%d, ration:%u,  id=%u, CurValue=%u, FinValue=%u, param1:%d,param2:%d,param3:%d cid:%lu ", missionId, missionIte->second->missionId, missionIte->second->items[i].type, missionIte->second->textId, missionIte->second->quality, missionIte->second->ration, missionIte->second->items[i].itemId,
					missionIte->second->items[i].currentValue, missionIte->second->items[i].finalValue, missionIte->second->items[i].parma1, missionIte->second->items[i].parma2, missionIte->second->items[i].parma3, cid);
			}
			m_pMaster->SendDataToClientEx(EMODULE_ID_TASK, LOGIC_TO_CLIENT_UPDATEMISSIONSTATUSNOTIFY, &notify);
		}	
	}
}

//删除任务
void MissionPart::NotifyDelMission(uint32_t dymissionId)
{
	ProtoBuf::GCDeleteMissionNotify notify;
	CharIDType cid = m_pMaster->GetCid();
	MMOLOG_FMT_DEBUG("[logic] Delete old DyMissionID=%u, cid:%lu ", dymissionId, cid);
	notify.add_dynamicid(dymissionId);
	m_pMaster->SendDataToClientEx(EMODULE_ID_TASK, LOGIC_TO_CLIENT_GCDELETEMISSIONNOTIFY, &notify);
}

//////////////////////////////////////////////////////////////////////////

void MissionPart::RegisterEvent(const uint32_t& eventType, const uint32_t& missionId, int32_t progressLev)
{
	EventTabal::iterator iter = _eventTabal.find(eventType);
	if (iter != _eventTabal.end())
	{
		MAP_INT32_SET_UINT32 &mapLevMission = iter->second;
		MAP_INT32_SET_UINT32::iterator iterLv = mapLevMission.find(progressLev);
		if (iterLv != mapLevMission.end())
		{
			iterLv->second.insert(missionId);
		}
		else
		{
			SET_UINT32 setMisson;
			setMisson.clear();
			setMisson.insert(missionId);
			mapLevMission[progressLev] = setMisson;
		}
	}
	else
	{
		MAP_INT32_SET_UINT32 mapLevMission;
		mapLevMission.clear();
		SET_UINT32 setMisson;
		setMisson.clear();
		setMisson.insert(missionId);
		mapLevMission[progressLev] = setMisson;
		_eventTabal[eventType] = mapLevMission;
	}
}

void MissionPart::RemoveEvent(const uint32_t& missionId)
{
	EventTabal::iterator iter = _eventTabal.begin();
	while (iter != _eventTabal.end())
	{
		MAP_INT32_SET_UINT32 &mapLevMission = iter->second;
		MAP_INT32_SET_UINT32::iterator iterLv = mapLevMission.begin();
		while (iterLv != mapLevMission.end())
		{
			SET_UINT32 &setMission = iterLv->second;
			SET_UINT32::iterator iterMission = setMission.find(missionId);
			if (iterMission != setMission.end())
			{
				setMission.erase(iterMission);
				if (setMission.size() <= 0)
				{
					iterLv = mapLevMission.erase(iterLv);
					continue;
				}
			}
			++iterLv;
		}
		if (mapLevMission.size() <= 0)
		{
			iter = _eventTabal.erase(iter);
			continue;
		}
		++iter;
	}
}

void MissionPart::OnEvent(const uint32_t& eventType, const ExecuteData& data)
{
	Player*pPlayer = dynamic_cast<Player*>(m_pMaster);
	if (nullptr == pPlayer)
	{
		LogErrFmtPrint("MissionPart::OnEvent...nullptr == pPlayer...eventType:%u ", eventType);
		return;
	}
	int32_t level = pPlayer->GetAttr(C_LEVEL);
	EventTabal::iterator iter = _eventTabal.find(eventType);
	if (_eventTabal.end() != iter)
	{
		MAP_INT32_SET_UINT32 &mapLvMission = iter->second;
		MAP_INT32_SET_UINT32::iterator iterLv = mapLvMission.begin();
		for (; iterLv != mapLvMission.end(); ++iterLv)
		{
			SET_UINT32 &setMission = iterLv->second;
			if (iterLv->first <= level)
			{
				SET_UINT32::iterator iterMission = setMission.begin();
				for (; iterMission != setMission.end(); ++iterMission)
				{
					g_GetMissionManager()->OnUpdateProgress(pPlayer, (*iterMission), data);
				}				
			}
		}
	}
}

bool MissionPart::HaveAccpet(const uint32_t& missionId)
{
	if (_playerTrackMissionMap.find(missionId) != _playerTrackMissionMap.end())
	{
		return true;
	}

	return false;
}

bool MissionPart::HaveChapterSubmit(const uint32_t& chapterId)//该章节是否已经提交过了
{
	SET_UINT32::iterator iter = _setSubmitChapter.find(chapterId);
	return (iter != _setSubmitChapter.end()) ? true : false;
}

bool MissionPart::HaveFinish(const uint32_t& missionId)
{
	PlayerTrackMissionMap::iterator iter = _playerTrackMissionMap.find(missionId);
	for (; iter != _playerTrackMissionMap.end(); ++iter)
	{
		if (iter->second->status == MISSION_E_COMPLETION)
		{
			return true;
		}
	}

	return false;
}

bool MissionPart::HaveNoFinish(const uint32_t& missionId)
{
	PlayerTrackMissionMap::iterator iter = _playerTrackMissionMap.find(missionId);
	if (iter != _playerTrackMissionMap.end())
	{
		if (iter->second->status == MISSION_E_ACCEPTED)
		{
			return true;
		}
	}

	return false;
}


//根据任务类型获取当前任务列表中存在的数量
int32_t	MissionPart::MissionNumByType(int32_t missionType)
{
	int32_t num = 0;
	PlayerTrackMissionMap::iterator iter = _playerTrackMissionMap.begin();
	for (; iter != _playerTrackMissionMap.end(); ++iter)
	{
		uint32_t missionId = iter->second->missionId;
		const DyMissionInfo *pDyMissionInfo = g_GetMissionManager()->GetDyMissionCfgInfo(missionId);
		if (nullptr != pDyMissionInfo)
		{
			if ((uint32_t)missionType == pDyMissionInfo->kind)
			{
				num++;
			}
		}
		else
		{
			MissionInfo *pMissionCfgInfo = g_GetMissionManager()->GetMissionCfgInfo(missionId);
			if (nullptr != pMissionCfgInfo)
			{
				if ((uint32_t)missionType == pMissionCfgInfo->kind)
				{
					num++;
				}
			}
		}
	}
	return num;
}
void MissionPart::MissionLstByType(int32_t missionType, SET_UINT32 &setAccept) //根据任务类型获取当前任务列表中存在的任务ID
{
	PlayerTrackMissionMap::iterator iter = _playerTrackMissionMap.begin();
	for (; iter != _playerTrackMissionMap.end(); ++iter)
	{
		uint32_t missionId = iter->second->missionId;
		uint32_t dymissionId = iter->second->dynamicId;
		const DyMissionInfo *pDyMissionInfo = g_GetMissionManager()->GetDyMissionCfgInfo(missionId);
		if (nullptr != pDyMissionInfo)
		{
			if ((uint32_t)missionType == pDyMissionInfo->kind)
			{
				setAccept.insert(dymissionId);
			}
		}
		else
		{
			MissionInfo *pMissionCfgInfo = g_GetMissionManager()->GetMissionCfgInfo(missionId);
			if (nullptr != pMissionCfgInfo)
			{
				if ((uint32_t)missionType == pMissionCfgInfo->kind)
				{
					setAccept.insert(dymissionId);
				}
			}
		}
	}
}

//根据任务类型获取已完成的次数
int32_t	MissionPart::HaveFinishNumByType(int32_t missionType)
{
	int32_t count = 0;
	PlayerDyMissionTrackMap::iterator iter = _mapDyMissionTrack.find(missionType);
	if (iter != _mapDyMissionTrack.end())
	{
		count = iter->second.finishNum;
	}

	return count;
}
uint64_t MissionPart::GetMissionFreshTime(int32_t missionType)	//根据任务类型获取刷新时间
{
	uint64_t fresh = 0;
	PlayerDyMissionTrackMap::iterator iter = _mapDyMissionTrack.find(missionType);
	if (iter != _mapDyMissionTrack.end())
	{
		fresh = iter->second.lastFresh;
	}

	return fresh;
}

void MissionPart::OnFinishDy(uint32_t dymissionId)	//完成任务
{
	PlayerTrackMissionMap::iterator iter = _mapBountyCanAccept.find(dymissionId);
	if (iter != _mapBountyCanAccept.end())
	{
		iter->second->status = MISSION_E_COMPLETION;
	}

	PlayerTrackMissionMap::iterator iterA = _mapCampCanAccept.find(dymissionId);
	if (iterA != _mapCampCanAccept.end())
	{
		iterA->second->status = MISSION_E_COMPLETION;
	}
}

void MissionPart::OnAbandonDy(uint32_t dymissionId,int32_t missionType)//放弃任务
{
	//除了打图任务，如果能放弃了，完成次数都需要+1,其他任务是不能放弃的
	if (MISSION_TYPE_ID_TREASURE != missionType)
	{
		uint64_t lastfresh = GetMissionFreshTime(missionType);
		uint32_t finishNum = HaveFinishNumByType(missionType);
		finishNum += 1;
		SetDyMissionTrack(missionType, finishNum, lastfresh);
	}
	//
	if (MISSION_TYPE_ID_BOUNTY == missionType)
	{
		PlayerTrackMissionMap::iterator iter = _mapBountyCanAccept.find(dymissionId);
		if (iter != _mapBountyCanAccept.end())
		{
			iter->second->status = MISSION_E_ABANDON;
		}
		else
		{
			//没找到，直接回收动态ID
			FreeDyMissionId(dymissionId);
		}
	}
	else if (MISSION_TYPE_ID_CAMP == missionType)
	{
		PlayerTrackMissionMap::iterator iterA = _mapCampCanAccept.find(dymissionId);
		if (iterA != _mapCampCanAccept.end())
		{
			//重新可接
			iterA->second->status = MISSION_E_ACCEPTABLE;
		}
		else
		{
			//没找到，直接回收动态ID
			FreeDyMissionId(dymissionId);
		}
	}
}

void MissionPart::OnSubmit(uint32_t missionId,uint32_t backMissionId, uint32_t chapterId, uint32_t kind) //提交任务
{
	const MissionInfo *pMissionInfo = g_GetMissionManager()->GetMissionCfgInfo(backMissionId);
	if (nullptr == pMissionInfo || pMissionInfo->chapterId != chapterId)
	{
		//主线和支线已提交章节需要记录
		if (MISSION_TYPE_ID_TRUNK == kind || MISSION_TYPE_ID_BRANCH == kind || MISSION_TYPE_ID_ADVENTURE == kind)
		{
			_setSubmitChapter.insert(chapterId);
		}
		//章节最后一个任务，章节完成奖励
		const MissionChapterInfo *pChapterCfg = g_GetMissionManager()->GetMissionChapterCfgInfo(chapterId);
		if (nullptr != pChapterCfg)
		{
			//章节固定奖励
			g_GetMissionManager()->AddReward(dynamic_cast<Player*>(m_pMaster), pChapterCfg->kind, const_cast<TASK_REWARD&>(pChapterCfg->finishAward));
			//章节随机奖励
			if (pChapterCfg->finishAwardRnd.size() > 0)
			{
				int32_t selidx = Random((uint32_t)pChapterCfg->finishAwardRnd.size());// 0 - pChapterCfg->finishAwardRnd.size() - 1
				TASK_REWARD reward;
				reward.push_back(pChapterCfg->finishAwardRnd[selidx]);
				g_GetMissionManager()->AddReward(dynamic_cast<Player*>(m_pMaster), pChapterCfg->kind, reward);
			}
		}
		//任务章节活跃度
		g_GetMissionManager()->TriggerOut(dynamic_cast<Player*>(m_pMaster), chapterId);
	}
	//主线任务处理
	if (MISSION_TYPE_ID_TRUNK == kind)
	{
		const MissionChapterInfo *pChapterCfg = g_GetMissionManager()->GetMissionChapterCfgInfo(chapterId);
		if (nullptr != pChapterCfg)
		{
			UpdateRecentSubmitTrunk(missionId, pChapterCfg->accept.camp, m_pMaster->GetAttr(C_RACE));

			//如果提交的任务阵营需求和当前玩家的阵营不一样，再检测一次主线任务
			if (pChapterCfg->accept.camp != (uint32_t)m_pMaster->GetAttr(C_CAMP_ID))
			{
				CheckTrunkMission();
			}
		}
		else
		{
			LogErrFmtPrint(" MissionPart::OnSubmit...cid:%lu,missionid:%u,backmissionid:%u,chapterid:%u,kind:%u ", m_pMaster->GetCid(), missionId, backMissionId, chapterId, kind);
		}
		//这里不在主动检查主线任务，主线任务检查只在登录的时候和切换阵营的时候
		//CheckTrunkMission();
	}	
}
//放弃任务
void MissionPart::OnAbandon(uint32_t chapterId)
{
	const MissionChapterInfo *pChapterCfg = g_GetMissionManager()->GetMissionChapterCfgInfo(chapterId);
	if (nullptr != pChapterCfg)
	{
		if (ECHAPTER_SAVE_TYPE_SUBMIT_RECORD == pChapterCfg->recordtype)
		{
			_setSubmitChapter.erase(chapterId);
		}
		else if (ECHAPTER_SAVE_TYPE_RECV_RECORD == pChapterCfg->recordtype)
		{
			//支线和奇遇已提交章节需要记录，主线的逻辑是不会到这里的
			if ( MISSION_TYPE_ID_BRANCH == pChapterCfg->kind || MISSION_TYPE_ID_ADVENTURE == pChapterCfg->kind)
			{
				_setSubmitChapter.insert(chapterId);
			}
		}
	}
	else
	{
		LogErrFmtPrint("MissionPart::OnAbandon...cid:%lu,chapterid:%u ", m_pMaster->GetCid(), chapterId);
	}
}

void MissionPart::OnSubmitDy(uint32_t dymissionId,int32_t missionType,int32_t quality)	//提交任务
{
	//工会和环任务不能放弃，每次提交之后，自动接取一个任务
	int32_t huoyue = 0;
	if (MISSION_TYPE_ID_CAMP == missionType)
	{
		huoyue = HYDT_MISSION_CAMP;
		//完成一个任务那么增加宝箱进度条
		_campBoxProgress += quality;
		//设置阵营任务状态
		PlayerTrackMissionMap::iterator iter = _mapCampCanAccept.find(dymissionId);
		if (iter != _mapCampCanAccept.end())
		{
			iter->second->status = MISSION_E_SUBMITTED;
		}
		else
		{
			//没找到，直接回收动态ID
			FreeDyMissionId(dymissionId);
		}
		//重新刷新新的阵营任务
		InitCampMission(true, true);
	}
	else if (MISSION_TYPE_ID_BOUNTY == missionType)
	{
		huoyue = HYDT_MISSION_BOUNTY;
		//设置赏金任务状态
		PlayerTrackMissionMap::iterator iter = _mapBountyCanAccept.find(dymissionId);
		if (iter != _mapBountyCanAccept.end())
		{
			iter->second->status = MISSION_E_SUBMITTED;
		}
		else
		{
			//没找到，直接回收动态ID
			FreeDyMissionId(dymissionId);
		}
	}
	else if (MISSION_TYPE_ID_GUILD == missionType)
	{
		huoyue = HYDT_MISSION_GUILD;
		AcceptMissionByType(MISSION_TYPE_ID_GUILD,true);
	}
	
	else if (MISSION_TYPE_ID_LOOP == missionType)
	{
		huoyue = HYDT_MISSION_LOOP;
		AcceptMissionByType(MISSION_TYPE_ID_LOOP,true);
	}
	else if (MISSION_TYPE_ID_TREASURE == missionType)
	{
		huoyue = HYDT_MISSION_TREASURE;
	}
	else if (MISSION_TYPE_ID_GUILD_DAILY == missionType)
	{
		huoyue = HYDT_MISSION_GUILD_DAILY;
	}
	else if (MISSION_TYPE_ID_DEPUTY_COLLECT == missionType)
	{
		huoyue = HYDT_MISSION_DEPUTY_COLLECT;
	}
	else if (MISSION_TYPE_ID_DAILY == missionType)
	{
		huoyue = HYDT_MISSION_DAILY;
		AcceptMissionByType(MISSION_TYPE_ID_DAILY, true);
	}
	else if (MISSION_TYPE_ID_ACT_COLLECT == missionType)
	{
		huoyue = HYDT_MISSION_ACT_COLLECT;
	}
	//
	if (huoyue > 0)
	{
		HuoYueDuPart* pHuoYueDuPart = dynamic_cast<HuoYueDuPart*>(m_pMaster->GetPart(PART_HUOYUEDU));
		if (nullptr != pHuoYueDuPart)
		{
			//增加活跃度
			pHuoYueDuPart->AddHuoYueDuRecord(huoyue);

			if (HYDT_MISSION_BOUNTY == huoyue || HYDT_MISSION_GUILD == huoyue || HYDT_MISSION_CAMP == huoyue)
			{
				FinishRiskEvent finishRisk;
				finishRisk.type = (HuoYueDuType)huoyue;
				g_GetEvent()->FireExecute(EVENT_FINISH_RISK, m_pMaster->GetCid(), CREATURE_PLAYER, (FinishRiskEvent*)&finishRisk, sizeof(FinishRiskEvent));
			}
		}
	}
}

//添加任务掉落
bool MissionPart::AddMissionDrop(uint32_t dymissionId, uint32_t monsId, uint32_t dropId, uint32_t boxId, int32_t progressLev)
{
	MissionAllDropMap::iterator iterMons = _mapMissionAllDrop.find(monsId);
	if (iterMons != _mapMissionAllDrop.end())
	{
		MissionDropMap &mapDrop = iterMons->second;
		MissionDropMap::iterator iterMission = mapDrop.find(dymissionId);
		if (iterMission != mapDrop.end())
		{
			return false;
		}
		else
		{
			MissionDrop stDrop;
			stDrop.dropId = dropId;
			stDrop.boxId = boxId;
			stDrop.progressLv = progressLev;
			mapDrop[dymissionId] = stDrop;
		}
	}
	else
	{
		MissionDropMap mapDrop;
		mapDrop.clear();
		MissionDrop stDrop;
		stDrop.dropId = dropId;
		stDrop.boxId = boxId;
		stDrop.progressLv = progressLev;
		mapDrop[dymissionId] = stDrop;
		_mapMissionAllDrop[monsId] = mapDrop;
	}
	return true;
}

//删除任务掉落
bool MissionPart::DelMissionDrop(uint32_t dymissionId, uint32_t monsId)
{
	MissionAllDropMap::iterator iterMons = _mapMissionAllDrop.find(monsId);
	if (iterMons != _mapMissionAllDrop.end())
	{
		MissionDropMap &mapDrop = iterMons->second;
		MissionDropMap::iterator iterMission = mapDrop.find(dymissionId);
		if (iterMission != mapDrop.end())
		{
			mapDrop.erase(iterMission);
			if (mapDrop.size() <= 0)
			{
				_mapMissionAllDrop.erase(iterMons);
			}
			//
			return true;
		}
	}
	return false;
}

//获取任务掉落
void MissionPart::GetMissionDrop(uint32_t monsterId, MissionDropMap &mapMissionDrop)
{
	MissionAllDropMap::iterator iterMons = _mapMissionAllDrop.find(monsterId);
	if (iterMons != _mapMissionAllDrop.end())
	{
		mapMissionDrop = iterMons->second;
	}
}

//使用物品接取任务
bool	MissionPart::AcceptMissionByUseItem(uint32_t chapterId)
{
	const MissionChapterInfo *pChaterCfg = g_GetMissionManager()->GetMissionChapterCfgInfo(chapterId);
	if (nullptr == pChaterCfg)
	{
		return false;
	}
	int32_t ret = g_GetMissionManager()->OnAccept(dynamic_cast<Player*>(m_pMaster), pChaterCfg->firstMissionId, true);
	if (RET_SUCCESS == ret)
	{
		LogDebugFmtPrint("AcceptMissionByUseItem...cid:%lu,missionid:%u,chapter:%u,camp:%d,race:%d ", m_pMaster->GetCid(), pChaterCfg->firstMissionId, chapterId, (int32_t)m_pMaster->GetAttr(C_CAMP_ID), (int32_t)m_pMaster->GetAttr(C_RACE));
	}


	return (RET_SUCCESS == ret);
}
//效果触发器触发接取任务
bool MissionPart::AcceptMissionByEffect(uint32_t chapterId)
{
	const MissionChapterInfo *pChaterCfg = g_GetMissionManager()->GetMissionChapterCfgInfo(chapterId);
	if (nullptr == pChaterCfg)
	{
		return false;
	}
	int32_t ret = g_GetMissionManager()->OnAccept(dynamic_cast<Player*>(m_pMaster), pChaterCfg->firstMissionId, true);
	if (RET_SUCCESS == ret)
	{
		LogDebugFmtPrint("AcceptMissionByEffect...cid:%lu,missionid:%u,chapter:%u,camp:%d,race:%d ", m_pMaster->GetCid(), pChaterCfg->firstMissionId, chapterId, (int32_t)m_pMaster->GetAttr(C_CAMP_ID), (int32_t)m_pMaster->GetAttr(C_RACE));
	}

	return (RET_SUCCESS == ret);
}
//奇遇系统 接取任务
int32_t MissionPart::AcceptMissionByAdventure(uint32_t chapterId)
{
	const MissionChapterInfo *pChaterCfg = g_GetMissionManager()->GetMissionChapterCfgInfo(chapterId);
	if (nullptr == pChaterCfg)
	{
		return false;
	}
	int32_t ret = g_GetMissionManager()->OnAccept(dynamic_cast<Player*>(m_pMaster), pChaterCfg->firstMissionId, true,true);
	if (RET_SUCCESS == ret)
	{
		LogDebugFmtPrint("AcceptMissionByAdventure...cid:%lu,missionid:%u,chapter:%u,camp:%d,race:%d ", m_pMaster->GetCid(), pChaterCfg->firstMissionId, chapterId, (int32_t)m_pMaster->GetAttr(C_CAMP_ID), (int32_t)m_pMaster->GetAttr(C_RACE));
	}
	else
	{
		LogErrFmtPrint("AcceptMissionByAdventure failed...cid:%lu,missionid:%u,chapter:%u,camp:%d,race:%d ", m_pMaster->GetCid(), pChaterCfg->firstMissionId, chapterId, (int32_t)m_pMaster->GetAttr(C_CAMP_ID), (int32_t)m_pMaster->GetAttr(C_RACE));
	}

	return ret;
}

void MissionPart::SetDyMissionTrack(int32_t missionType, int32_t finishNum, uint64_t lastFresh) //设置动态任务数据
{
	PlayerDyMissionTrackMap::iterator iter = _mapDyMissionTrack.find(missionType);
	if (iter != _mapDyMissionTrack.end())
	{
		iter->second.finishNum = finishNum;
		iter->second.lastFresh = lastFresh;
	}
	else
	{
		DyMissionTrack info;
		info.kind = missionType;
		info.finishNum = finishNum;
		info.lastFresh = lastFresh;
		_mapDyMissionTrack[missionType] = info;
	}
}
//设置任务开启
void MissionPart::SetMissionOpen(int32_t missionType, bool openFlag)
{
	_mapMissionOpen[missionType] = (int8_t)openFlag;
}
//任务是否开启
bool MissionPart::MissionOpen(int32_t missionType)
{
	MAP_INT32_INT8::iterator iter = _mapMissionOpen.find(missionType);
	return (iter != _mapMissionOpen.end()) ? iter->second : false;
}
//活动状态更新
void MissionPart::OnActivityState(uint32_t actId)
{
	CheckMissionOpen(MISSION_TYPE_ID_ACT_COLLECT);
	CheckActCollectMission(true);
}

void MissionPart::CheckMissionTimeout(bool notify/* = true*/) //检查任务超时
{
	uint64_t curTime = g_GetGlobalServerTime()->UnixSec();
	PlayerTrackMissionMap::iterator iter = _playerTrackMissionMap.begin();
	for (; iter != _playerTrackMissionMap.end(); ++iter)
	{
		const MissionInfo *pMissionInfo = g_GetMissionManager()->GetMissionCfgInfo(iter->second->missionId);
		if (nullptr == pMissionInfo || pMissionInfo->timeout <= 0)
		{
			continue;
		}
		if (iter->second->status != MISSION_E_ACCEPTED)
		{
			continue;
		}
		if (curTime - iter->second->acceptMissionTime >= (uint64_t)pMissionInfo->timeout)
		{
			//超时，任务失败，修改状态
			iter->second->status = MISSION_E_FAILURE;
			//打印日志
			for (uint32_t i = 0; i < iter->second->items.size(); i++)
			{
				MMOLOG_FMT_DEBUG("[logic] CheckMissionTimeout Mission Failed...dynamicid=%u,mission=%u, type=%u,textid:%u, quality:%d, ration:%u,  id=%u, CurValue=%u, FinValue=%u, param1:%d,param2:%d,param3:%d cid:%lu ", iter->second->dynamicId, iter->second->missionId, iter->second->items[i].type, iter->second->textId, iter->second->quality, iter->second->ration, iter->second->items[i].itemId,
					iter->second->items[i].currentValue, iter->second->items[i].finalValue, iter->second->items[i].parma1, iter->second->items[i].parma2, iter->second->items[i].parma3, m_pMaster->GetCid());
			}

			if (notify)
			{
				//通知任务状态改变
				UpdateMissionProgress(iter->second->dynamicId);
			}
		}
	}
}

bool MissionPart::HaveAcceptChapter(const uint32_t &chapterId)//是否已接取过章节
{
	PlayerTrackMissionMap::iterator iter = _playerTrackMissionMap.begin();
	for (; iter != _playerTrackMissionMap.end(); ++iter)
	{
		MissionInfo *pMissionInfo = g_GetMissionManager()->GetMissionCfgInfo(iter->second->missionId);
		if (nullptr != pMissionInfo && pMissionInfo->chapterId == chapterId)
		{
			return true;
		}
	}

	return false;
}

void MissionPart::CheckTrunkMission(bool notify/* = true*/) //检查主线任务
{
	int32_t num = MissionNumByType(MISSION_TYPE_ID_TRUNK);
	if (num > 0)
	{
		return;
	}
	//如果没有主线任务，需要根据阵营自动接取一个任务
	int32_t camp = m_pMaster->GetAttr(C_CAMP_ID);
	int32_t race = m_pMaster->GetAttr(C_RACE);
	uint32_t acceptMissionId = 0;
	uint32_t submitMission = GetRecentSubmitTrunk(camp, race);
	if (submitMission > 0)
	{
		MissionInfo *pMissionInfo = g_GetMissionManager()->GetMissionCfgInfo(submitMission);
		if (nullptr != pMissionInfo)
		{
			acceptMissionId = pMissionInfo->backTaskId;
		}
		else
		{
			MMOLOG_FMT_ERROR("MissionPart::CheckTrunkMission...can not find mission cfg..cid:%lu,mission:%u,camp:%d,race:%d ", m_pMaster->GetCid(), submitMission, camp,race);
		}
	}
	else
	{
		//根据阵营和种族，取第一个章节
		uint32_t chapterId = g_GetMissionManager()->GetFirstChapter(camp, race);
		const MissionChapterInfo *pChapterCfg = g_GetMissionManager()->GetMissionChapterCfgInfo(chapterId);
		if (nullptr != pChapterCfg)
		{
			acceptMissionId = pChapterCfg->firstMissionId;
		}
		else
		{
			MMOLOG_FMT_ERROR("MissionPart::CheckTrunkMission...can not find first chapter cfg..cid:%lu,chapterid:%u,camp:%d,race:%d ", m_pMaster->GetCid(), chapterId, camp,race);
		}
	}

	MissionInfo *pAcceptMissionInfo = g_GetMissionManager()->GetMissionCfgInfo(acceptMissionId);
	if (nullptr != pAcceptMissionInfo)
	{
		int32_t ret = g_GetMissionManager()->OnAccept(dynamic_cast<Player*>(m_pMaster), acceptMissionId, notify);
		if (RET_SUCCESS != ret)
		{
			MMOLOG_FMT_ERROR("MissionPart::CheckTrunkMission...OnAccept failed...cid:%lu,mission:%u,camp:%d,race:%d,ret:%d ", m_pMaster->GetCid(), acceptMissionId, camp,race,ret);
		}
		else
		{
			LogDebugFmtPrint("MissionPart::CheckTrunkMission...accept mission...cid:%lu,mission:%u,chapter:%u,camp:%d,race:%d ", m_pMaster->GetCid(), acceptMissionId, pAcceptMissionInfo->chapterId, camp, race);
		}
	}
	else
	{
		MMOLOG_FMT_ERROR("MissionPart::CheckTrunkMission...can not find accept mission cfg..cid:%lu,mission:%u,camp:%d,race:%d ", m_pMaster->GetCid(), acceptMissionId, camp,race);
	}

}
//杀怪掉落
void MissionPart::MissionDropByKillMons(uint32_t monsId,int32_t monsLev, Point3<float> &pos)
{
	int32_t level = m_pMaster->GetAttr(C_LEVEL);
	MissionDropMap mapMissionDrop;
	mapMissionDrop.clear();
	VEC_INT32 vecBox;
	vecBox.clear();
	GetMissionDrop(monsId, mapMissionDrop);
	MissionDropMap::iterator iter = mapMissionDrop.begin();
	for (; iter != mapMissionDrop.end(); ++iter)
	{
		if (!HaveNoFinish(iter->first))
		{
			continue;
		}

		MissionDrop &drop = iter->second;
		if (level < drop.progressLv)//进度等级不足
		{
			continue;
		}

		if (drop.dropId > 0)
		{
			SDropSourcePram source;
			g_GetDropMgr()->AddDrop(m_pMaster, pos, drop.dropId, monsId, monsLev, source);
		}
		if (drop.boxId > 0)
		{
			vecBox.push_back((int32_t)drop.boxId);
		}
	}
	if (vecBox.size() > 0)
	{
		SItemSourceParam sourceParam;
		g_GetDropMgr()->PlayerAddBox(dynamic_cast<Player*>(m_pMaster), vecBox, sourceParam);
	}
}
//共享杀怪
void MissionPart::ShareKillMons(uint32_t monsId, CharIDType killerCid, int32_t monsLev, int32_t count, Point3<float> &pos)
{
	//杀怪物计数
	ExecuteData executeData;
	executeData.type = M_EVENT_KILL_MONSTER;
	executeData.id = monsId;
	executeData.count = count;
	executeData.killer = m_pMaster->GetCid();
	OnEvent(M_EVENT_KILL_MONSTER, executeData);
	//杀怪共享任务掉落
	ShareMissionDropByKillMons(monsId, monsLev, count, pos);
	if (killerCid == m_pMaster->GetCid())
	{
		//打怪收集		格式 302=物品id=物品数量=怪物id=宝箱id=追踪区域id
		//采集怪物		格式 305=物品id=物品数量=可采集怪物id=宝箱id=0
		//杀怪掉落
		MissionDropByKillMons(monsId, monsLev, pos);
	}
}

//杀怪共享任务掉落
void MissionPart::ShareMissionDropByKillMons(uint32_t monsId,int32_t monsLev, int32_t count, Point3<float> &pos)
{
	//打怪收集		格式 302=物品id=物品数量=怪物id=掉落包id=追踪区域id
	MissionDropMap mapMissionDrop;
	mapMissionDrop.clear();
	VEC_INT32 vecBox;
	vecBox.clear();
	GetMissionDrop(monsId, mapMissionDrop);
	MissionDropMap::iterator iter = mapMissionDrop.begin();
	for (; iter != mapMissionDrop.end(); ++iter)
	{
		uint32_t dymissionId = iter->first;
		MissionDrop &drop = iter->second;
		if (!HaveNoFinish(dymissionId))
		{
			continue;
		}
		PlayerTrackMissionMap::iterator iterMission = _playerTrackMissionMap.find(dymissionId);
		if (iterMission == _playerTrackMissionMap.end())
		{
			continue;
		}
		bool flag = false;
		vector<ItemInfo>::iterator iterCond = iterMission->second->items.begin();
		for (; iterCond != iterMission->second->items.end(); ++iterCond)
		{
			ItemInfo &cond = (*iterCond);
			if (MISSION_FINISH_TYPE_COLLECT_KILL_MONS == cond.type) //打怪收集类型的才能共享
			{
				flag = true;
				break;
			}
		}
		if (flag)
		{
			if (drop.dropId > 0)
			{
				SDropSourcePram source;
				g_GetDropMgr()->AddDrop(m_pMaster, pos, drop.dropId, monsId, monsLev, source);
			}
			if (drop.boxId > 0)
			{
				vecBox.push_back((int32_t)drop.boxId);
			}
		}
	}
	if (vecBox.size() > 0)
	{
		SItemSourceParam sourceParam;
		g_GetDropMgr()->PlayerAddBox(dynamic_cast<Player*>(m_pMaster), vecBox, sourceParam);
	}
}

uint32_t MissionPart::AllocNewDyMisssionId()//分配一个动态任务ID
{
	for (uint32_t i = 1; i <= MISSION_MAX_DYNAMIC_ALLOC; ++i)
	{
		if (!_aryDyIdAlloc[i])
		{
			_aryDyIdAlloc[i] = 1;
			return i;
		}
	}
	return 0;
}

void MissionPart::FreeDyMissionId(uint32_t dyMissionId)	//回收一个动态任务ID
{
	if (dyMissionId >= 1 && dyMissionId <= MISSION_MAX_DYNAMIC_ALLOC)
	{
		_aryDyIdAlloc[dyMissionId] = 0;
	}
}

bool MissionPart::ValidDyMissionId(uint32_t dyMissionId) //是否是有效的动态任务ID
{
	if (dyMissionId >= 1 && dyMissionId <= MISSION_MAX_DYNAMIC_ALLOC)
	{
		return true;
	}
	return false;
}

void MissionPart::CheckCampMission(bool bFresh, bool notify) //检查阵营任务开启
{
	if (MissionOpen(MISSION_TYPE_ID_CAMP))
	{
		InitCampMission(bFresh, notify);
	}
	else
	{
		ClearMissionByType(MISSION_TYPE_ID_CAMP,notify);
	}
}

void MissionPart::CheckGuildMission(bool notify /*= false*/) //检查工会任务开启
{
	if (!MissionOpen(MISSION_TYPE_ID_GUILD))
	{
		ClearMissionByType(MISSION_TYPE_ID_GUILD, notify);
	}
}

void MissionPart::CheckGuildDailyMission(bool notify/* = false*/)//检查工会日常任务开启
{
	if (!MissionOpen(MISSION_TYPE_ID_GUILD_DAILY))
	{
		ClearMissionByType(MISSION_TYPE_ID_GUILD_DAILY, notify);
	}
}

void MissionPart::CheckBanishMission(bool notify/* = false*/)//登录检查流放之地任务
{
	int32_t mapId = m_pMaster->GetMapId();
	const ConstantConstantCfgInfo *pBanishMap = g_GetConstantConstantCfgTable()->GetConstantConstantCfgInfo(EArg_ClearPoint_Jail);
	if (nullptr != pBanishMap && pBanishMap->constantdata != mapId)
	{
		ClearMissionByType(MISSION_TYPE_ID_BANISH, notify);
	}

}

void MissionPart::CheckActCollectMission(bool notify/* = false*/)	//检查活动收集任务
{
	if (!MissionOpen(MISSION_TYPE_ID_ACT_COLLECT))
	{
		ClearMissionByType(MISSION_TYPE_ID_ACT_COLLECT, notify);
	}
	else
	{
		//如果已经开启，需要清除掉不在当前 活动时间内接取的任务
		ClearMissionByActTime(MISSION_TYPE_ID_ACT_COLLECT, notify);
	}
}

bool MissionPart::IsNeedFresh(uint64_t nowTime, int32_t missionType, uint64_t lastTime)	//指定任务类型是否需要刷新
{
	const TasktypeTasktypeCfgInfo *pTaskTypeCfg = g_GetTasktypeTasktypeCfgTable()->GetTasktypeTasktypeCfgInfo(missionType);
	if (nullptr != pTaskTypeCfg)
	{
		if (MISSION_UPDATE_DAY == pTaskTypeCfg->refreshTime)
		{
			if (TimeUtility::CheckDayUpdate(nowTime, lastTime))
			{
				return true;
			}
		}
		else if (MISSION_UPDATE_WEEK == pTaskTypeCfg->refreshTime)
		{
			if (TimeUtility::CheckWeekUpdate(nowTime, lastTime))
			{
				return true;
			}
		}
	}
	return false;
}

void MissionPart::CheckMissionFresh()//检查任务重置
{
	uint64_t nowTime = g_GetGlobalServerTime()->UnixSec();
	const TasktypeTasktypeCfgMap *pTaskTypeMap = g_GetTasktypeTasktypeCfgTable()->GetTasktypeTasktypeCfgMap();
	if (nullptr != pTaskTypeMap)
	{
		TasktypeTasktypeCfgMap::const_iterator iter = pTaskTypeMap->begin();
		for (; iter != pTaskTypeMap->end(); ++iter)
		{
			const TasktypeTasktypeCfgInfo &info = iter->second;
			uint64_t freshTime = GetMissionFreshTime(info.tasktypeID);
			if (MISSION_UPDATE_DAY == info.refreshTime)
			{
				if (TimeUtility::CheckDayUpdate(nowTime,freshTime))
				{
					MissionFresh(info.tasktypeID, nowTime);
				}				
			}
			else if (MISSION_UPDATE_WEEK == info.refreshTime)
			{
				if (TimeUtility::CheckWeekUpdate(nowTime, freshTime))
				{
					MissionFresh(info.tasktypeID, nowTime);
				}
			}
		}
	}
}
//重置指定任务类型的任务
void MissionPart::MissionFresh(int32_t missionType, uint64_t nowTime)	
{
	//周期内已完成次数和上次刷新时间
	int32_t finishNum = HaveFinishNumByType(missionType);
	uint64_t freshTime = GetMissionFreshTime(missionType);
	//
	if (MISSION_TYPE_ID_CAMP == missionType)
	{
		//检查是否已接，如果已接，不刷新,同时重置已完成次数，如果未接，重置时间和次数，同时刷新可接列表
		if (MissionNumByType(missionType) > 0)
		{
			finishNum = 0;
		}
		else
		{
			finishNum = 0;
			freshTime = nowTime;
		}
		//设置动态任务信息
		SetDyMissionTrack(missionType, finishNum, freshTime);
		//重新刷新阵营任务
		InitCampMission(true, true);
	}
	else if (MISSION_TYPE_ID_BOUNTY == missionType)
	{
		//清空赏金任务周期内已经接取次数
		_bountyAccetpNum = 0;
		//重置免费次数
		_bountyFreeNum = 0;
		//重置周期内已完成次数
		SetDyMissionTrack(missionType, 0, freshTime);
	}
	else
	{
		//设置动态任务信息
		SetDyMissionTrack(missionType, 0, nowTime);
		//
		if (MISSION_TYPE_ID_LOOP == missionType)
		{
		}
		else if (MISSION_TYPE_ID_GUILD == missionType)
		{
		}
	}
}